How to sort an array from multiple textfields with one property - swift

I was looking for an answer for this question but I couldn't find anything. I'm new in swift programming and also in stackoverflow, so I hope anyone can help me.
I try to make an app with an "EditViewController" which is there with multiple textfields for name, prename, etc.
I'm able to save this "phonebook" entries, but I'm not able to sort the array by the property name.
The editing interface is only this code:
import UIKit
class EditViewController: UIViewController {
#IBOutlet weak var vornameTextField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var adresseTextField: UITextField!
#IBOutlet weak var hausnummerTextField: UITextField!
#IBOutlet weak var plzTextField: UITextField!
#IBOutlet weak var ortTextField: UITextField!
#IBOutlet weak var telefonnummerTextField: UITextField!
#IBOutlet weak var berufTextField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
The code for saving the textfields is:
import UIKit
class Telefonbuch: NSObject, NSCoding
{
var name: String!
var vorname: String!
var beruf: String!
var telefonnummer: String!
var adresse: String!
var hausnummer: String!
var plz: String!
var ort: String!
init(name: String, vorname: String, beruf:String, telefonnummer: String, adresse: String, hausnummer: String, plz: String, ort: String)
{
self.name = name
self.vorname = vorname
self.beruf = beruf
self.telefonnummer = telefonnummer
self.adresse = adresse
self.hausnummer = hausnummer
self.plz = plz
self.ort = ort
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObjectForKey("name") as? String
vorname = aDecoder.decodeObjectForKey("vorname") as? String
beruf = aDecoder.decodeObjectForKey("beruf") as? String
telefonnummer = aDecoder.decodeObjectForKey("telefonnummer") as? String
adresse = aDecoder.decodeObjectForKey("adresse") as? String
hausnummer = aDecoder.decodeObjectForKey("hausnummer") as? String
plz = aDecoder.decodeObjectForKey("plz") as? String
ort = aDecoder.decodeObjectForKey("ort") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(vorname, forKey: "vorname")
aCoder.encodeObject(beruf, forKey: "beruf")
aCoder.encodeObject(telefonnummer, forKey: "telefonnummer")
aCoder.encodeObject(adresse, forKey: "adresse")
aCoder.encodeObject(hausnummer, forKey: "hausnummer")
aCoder.encodeObject(plz, forKey: "plz")
aCoder.encodeObject(ort, forKey: "ort")
}
static func saveArray(data: [Telefonbuch])
{
if data.count == 0 {return}
if let path = getFilePath() {
NSKeyedArchiver.archiveRootObject(data, toFile: path)
}
}
static func loadArray() -> [Telefonbuch]
{
if let path = getFilePath() {
if let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [Telefonbuch]
{
return result
}
}
return [Telefonbuch]()
}
private static func getFilePath() -> String?
{
let pfd = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
if let pfad = pfd.first {
return pfad + "Kontakte.bin"
}else {
return nil
}
}
}
Now I would like to make the tableview, where I display the data, sorted and with header. But I'm not able to sort the [Telefonbuch] Array by property name.
import UIKit
class OverViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var editButton: UINavigationItem!
var kontaktListe = Telefonbuch.loadArray()
override func viewDidLoad()
{
super.viewDidLoad()
tableView.dataSource = self
tableView.reloadData()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
#IBAction func addButtonPressed(sender: AnyObject)
{
performSegueWithIdentifier("editSegue", sender: self)
}
#IBAction func returnToMainController(segue: UIStoryboardSegue)
{
if let scr = segue.sourceViewController as? EditViewController
{
let newvorname = scr.vornameTextField.text
let newname = scr.nameTextField.text
let newadresse = scr.adresseTextField.text
let newhausnummer = scr.hausnummerTextField.text
let newpostleitzahl = scr.plzTextField.text
let newort = scr.ortTextField.text
let newtelefonnummer = scr.telefonnummerTextField.text
let newberuf = scr.berufTextField.text
let newKontakt = Telefonbuch(name: newname!, vorname: newvorname!, beruf: newberuf!, telefonnummer: newtelefonnummer!, adresse: newadresse!, hausnummer: newhausnummer!, plz: newpostleitzahl!, ort: newort!)
kontaktListe.insert(newKontakt, atIndex: 0)
Telefonbuch.saveArray(kontaktListe)
tableView.reloadData()
}
}
extension OverViewController: UITableViewDataSource
{
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return kontaktListe.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ProtoCell", forIndexPath: indexPath)
let row = indexPath.row
cell.textLabel?.text = kontaktListe[row].name + " " + kontaktListe[row].vorname
cell.detailTextLabel?.text = kontaktListe[row].ort
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
kontaktListe.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.reloadData()
}
}
extension OverViewController: UITableViewDelegate
{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
performSegueWithIdentifier("detailSegue", sender: self)
}
}
Can anyone help me because I don't find a solution.
Thanks in advance.

You should be able to sort the array with:
kontaktListe.sort({ $0.name > $1.name })

Related

XCode 12/Swift 4 Custom Cells not displaying on UI Table Cell View

Ok so, I am trying to make a custom table that has a news feed from newsapi, from my debugging: the api calls and such get made and the data is acessed, its just that it doesnt display on the table, it shows up as a blank table.
Here is the code:
This is from the "first view controller" as I am using the tabbed template
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var articles: [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
fetchArticles()
}
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?country=us&?category=business&apiKey=sorrynotgivingmykey")!)
let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error) in
if error != nil{
print(error)
return
}
self.articles = [Article]()
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["articles"] as? [[String: AnyObject]]{
for articlesFromJson in articlesFromJson{
let article = Article()
if let title = articlesFromJson["title"] as? String, let desc = articlesFromJson["description"] as? String, let url = articlesFromJson["url"] as? String, let imageToUrl = articlesFromJson["urlToImage"] as? String, let date = articlesFromJson["publishedAt"] as? String{
article.headline = title
article.desc = desc
article.url = url
article.imageUrl = imageToUrl
article.date = date
// print(article.date)
// print(article.headline)
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch let error{
print(error)
}
}
task.resume()
// print(articles)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "worklmao", for: indexPath) as! ArticleCell
cell.title.text = self.articles?[indexPath.item].headline
cell.desc.text = self.articles?[indexPath.item].desc
cell.date.text = self.articles?[indexPath.item].date
print("lol lmao hahax help fuck shit")
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
1
}
}
And this is the cell classes I used for the articles
import UIKit
class ArticleCell: UITableViewCell {
#IBOutlet weak var date: UILabel!
#IBOutlet weak var desc: UILabel!
#IBOutlet weak var title: UILabel!
#IBOutlet weak var ImgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is the article class
import UIKit
class Article: NSObject {
var headline: String?
var desc: String?
var url: String?
var date: String?
var imageUrl: String?
}
and bare in mind I did setup the class for the cell properly(at least I think
Still, this is what I get:
Don't forget to connect dataSource and delegate for tableView.
Change your tableView outlets to this:
#IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
Some points:
You don't have to declare articles array as optional. Simply do this :
var articles = [Article]()
Try to learn about codables for JSON parsing.

All Items From Array Not In UITableView

Below is the CatalogViewController, which holds a tableview. The tableview has 1 prototype cell, ShopCell. When I print the items in the loop, they print correct, but when shown in the table, items are missing.
(Removing the shuffle() method does nothing & removing removeDuplicates(), items appear more than once). I didn't include the addToFavorites(cell: ShopCell) because I'm testing it. It does nothing.
protocol ShopCellDelegate {
func addToFavorites(cell: ShopCell)
}
class ShopCell: UITableViewCell {
#IBOutlet weak var productImageView: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var descTV: UITextView!
#IBOutlet weak var favoriteButton: UIButton!
var delegate: ShopCellDelegate?
override func prepareForReuse() {
super.prepareForReuse()
self.productImageView.image = nil
self.titleLabel.text = ""
self.priceLabel.text = ""
self.descTV.text = ""
self.favoriteButton.isHidden = true
}
func setProduct(product: Product) {
productImageView.sd_setImage(with: URL(string: product.urlToImage!), placeholderImage: UIImage(named: "1024ELP.png"))
titleLabel.text = product.itemName!
priceLabel.text = product.priceTag!
descTV.text = product.itemDesc!
}
#IBAction func favOrUnfav(_ sender: UIButton) {
if let delegate = self.delegate {
delegate.addToFavorites(cell: self)
}
}
}
//
class CatelogViewController: UIViewController, GADInterstitialDelegate, SFSafariViewControllerDelegate, UITableViewDelegate, UITableViewDataSource, ShopCellDelegate {
#IBOutlet weak var tableView: UITableView!
static var shopType = String()
static var linkToVisit = String()
var myProducts = [Product]()
var productKeys = [String]()
var interstitial: GADInterstitial!
override func viewWillAppear(_ animated: Bool) {
visuals() // Sets Nav Bar color & changes cell size if device == ipad
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.navigationController?.navigationBar.tintColor = UIColor.black
if CatelogViewController.shopType == "Apparel" {
self.title = NSLocalizedString("Shop Apparel", comment: "")
fetchProductLinks(child1: "ProductList", child2: "Products")
}else{
self.title = NSLocalizedString("Shop Others", comment: "")
fetchProductLinks(child1: "OtherList", child2: "OtherProducts")
//shuffleItems()
}
if let index = self.tableView.indexPathForSelectedRow{
self.tableView.deselectRow(at: index, animated: true)
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myProducts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ShopCell
let product = myProducts[indexPath.row]
cell.delegate = self
cell.favoriteButton.isHidden = true
cell.setProduct(product: product)
return cell
}
func fetchProductLinks(child1: String, child2: String) {
let ref = Database.database().reference()
let prodRef = ref.child(child1).child(child2)
prodRef.observeSingleEvent(of: .value, with: { snapshot in
self.myProducts.removeAll()
for items in snapshot.children {
let item = items as! DataSnapshot
let product = item.value as! [String : String]
let name = product["Name"]
let link = product["Link"]
let img = product["urlToImage"]
let desc = product["Description"]
let price = product["Price"]
let newProduct = Product(urlToImage: img, itemName: name, itemLink: link, itemDesc: desc, priceTag: price)
self.myProducts.append(newProduct)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
self.myProducts = self.shuffleArray(array: self.myProducts) as! [Product]
self.myProducts = self.myProducts.removeDuplicates()
})
ref.removeAllObservers()
}
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}
You shuffle your array and you remove duplicates, but you don't reload data after it. So reload data of table view
self.myProducts = self.shuffleArray(array: self.myProducts) as! [Product]
self.myProducts = self.myProducts.removeDuplicates()
self.tableView.reloadData()

How to retrieve an array of data from Firebase into iOS App

I am trying to retrieve this from my Firebase DB:
And this my VC, where I retrieve data from DB:
//
// VestibularesViewController_Design.swift
// newProject
//
// Created by Lucas Nascimento on 31/05/18.
// Copyright © 2018 Lucas Frazao. All rights reserved.
//
import UIKit
import Firebase
class VestibularesViewController_Design: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var topView: UIView!
#IBOutlet weak var tableView: UITableView!
#IBOutlet var backgroundView: UIView!
#IBOutlet weak var nomeVestibular: UILabel!
var ref: DatabaseReference!
var databaseHandle: DatabaseHandle?
var datas = [Datas]()
var newItems: [Datas] = []
var meses = ["Maio","Junho","Agosto", "Agosto"]
var ano = ["2018", ""]
var dias = ["18","20", "30", "31"]
var eventos = ["Inicio das inscrições", "Fim das inscricoes", "1ª Prova", "2ª Prova"]
override func viewDidLoad() {
super.viewDidLoad()
nomeVestibular.text = "ENEM"
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
loadPosts()
}
func numberOfSections(in tableView: UITableView) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func loadPosts() {
Database.database().reference().child("Datas").observe(.childAdded, with: { (snapshot) in
DispatchQueue.main.async {
self.tableView.reloadData();
}
if let dict = snapshot.value as? [String: [Any]] {
let diaText = dict["dia"] as? String
let mesText = dict["mes"] as? String
let eventoText = dict["evento"] as? String
// let dateText = dict["date"] as? String
let data = Datas(diaText: diaText, mesText: mesText, eventoText: eventoText)
self.newItems.append(data)
print(self.newItems)
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"cell", for: indexPath) as! VestibularesTableViewCell
//cell.titleNews.text = "O Edital do ENEM foi anunciado!"
ref = Database.database().reference()
cell.dia.text = datas[0].dia
cell.evento.text = datas[indexPath.row].evento
cell.mes.text = datas[indexPath.row].mes
if backgroundView.backgroundColor == UIColor.white {
cell.mes?.textColor = UIColor.black
cell.dia?.textColor = UIColor.black
cell.evento?.textColor = UIColor.black
}
return cell
}
override func viewWillDisappear(_ animated: Bool) {
//self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If I try to load one value for each row, it works fine, but I can't get it to retrieve the array.
And this is where I created the class "Datas":
class Datas {
var dia: String?
var mes: String?
var evento: String?
init(diaText: String?, mesText: String?, eventoText: String?) {
dia = diaText
mes = mesText
evento = eventoText
}
}
I think something related to the class Datas needs to be changed in order for it to work properly.
You're trying to read the array into a string here:
let eventoText = dict["evento"] as? String
And that won't work. I'm not a Swift expert, but most likely it needs to be:
let eventoText = dict["evento"] as? [String]

how to pass data retrieve from firebase in Table VIew Controller to View Controller

I am building a car sharing IOS App prototype. My app is link to firebase, i can retrieve and display journey data in a table view but when trying to pass the data in another view controller the data do not display. Below are my table View controller and view controllers source codes.
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myIndex = 0
var journeyList = [journeyModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return journeyList.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
// defining firebase reference var
var refjourney: DatabaseReference!
#IBOutlet weak var journeyTable: UITableView!
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath as IndexPath) as! journeySearchTableViewCell
var journe: journeyModel
journe = journeyList[indexPath.row]
print(journe.start!, journe.destination!, journe.date!, journe.driverName!)
cell.driverNameLabel.text = journe.driverName
cell.startLabel.text = journe.start
cell.destinationLabel.text = journe.destination
cell.dateLabel.text = journe.date
return cell
}
At this point the app functions correctly only faces issues when passing the data to another view controller
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Journey").observe(.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
self.journeyList.removeAll()
for journey in snapshot.children.allObjects as! [DataSnapshot] {
let journeyObject = journey.value as? [String: AnyObject]
let start = journeyObject?["startingPoint"]
let destination = journeyObject?["destinationPoint"]
let driverName = journeyObject?["driverName"]
let date = journeyObject?["tripDate"]
let id = journeyObject?["id"]
let journey = journeyModel(destination: destination as! String?, driverName: driverName as! String?, start: start as! String?, date: date as! String?, uid: id as! String?)
self.journeyList.append(journey)
}
self.journeyTable.reloadData()
}
})
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "logged", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var bsVC: bookSetViewController = segue.destination as! bookSetViewController
}
#IBAction func backButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
import UIKit
class bookSetViewController: UIViewController {
var getStart = String()
var getStop = String()
var getDate = String()
var getDriver = String()
#IBOutlet weak var startingLabel: UILabel!
#IBOutlet weak var stopingLabel: UILabel!
#IBOutlet weak var daterLabel: UILabel!
#IBOutlet weak var driveLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
startingLabel.text! = getStart
stopingLabel.text! = getStop
daterLabel.text! = getDate
driveLabel.text! = getDriver
}
}
import UIKit
class journeySearchTableViewCell: UITableViewCell {
#IBOutlet weak var startLabel: UILabel!
#IBOutlet weak var destinationLabel: UILabel!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var driverNameLabel: UILabel!
}
import UIKit
class journeyModel: NSObject {
var driverName: String?
var start: String?
var destination: String?
var date: String?
var uid: String?
init(destination: String?, driverName: String?, start: String?, date: String?, uid: String?) {
self.driverName = driverName
self.start = start
self.destination = destination
self.date = date
self.uid = uid
}
}
First things, first - don't share the whole project, just the bits that are needed.
The whole point of the prepare(for segue... is to get a handle to the new controller, and assign the values you need to pass over.
You will need to keep a track of which journey you're interested in. There are many ways to do this, but the easiest might be to extend what you do on the click row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// assume you have defined journeySelected as a class-level instance of journeyModel
journeySelected = journeyModel[indexPath.row]
performSegue(withIdentifier: "logged", sender: self)
}
and then
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var bsVC: bookSetViewController = segue.destination as! bookSetViewController
bsVC.getStart = journeySelected.start
// and for all the other fields
}

How can I return multiple elements in a cell?

I would like to return multiple elements of a cell. How can I do it? This is the code I'm working on
//
// TableViewControllerCompiti.swift
// Secondo B
//
// Created by Edoardo on 23/12/15.
// Copyright © 2015 ERC. All rights reserved.
//
import UIKit
import Parse
class TableViewControllerCompiti: UITableViewController {
var selfTable: NSMutableArray = NSMutableArray()
#IBOutlet var MessageTable: UITableView!
#IBOutlet weak var Compiti: UILabel!
#IBOutlet weak var DescrizioneCompiti: UITextView!
#IBOutlet weak var DataCompiti: UILabel!
var messagesArray: [String] = [String]()
var descriptionArray: [String] = [String]()
var dateArray: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
func retrieveMessages() {
let query = PFQuery(className: "Compiti")
query.findObjectsInBackgroundWithBlock {
(remoteObjects: [PFObject]?, error: NSError?) -> Void in
for messageObject in remoteObjects! {
let messageText: String? = (messageObject as PFObject) ["Materia"] as? String
let descriptionText: String? = (messageObject as PFObject) ["Compiti"] as? String
let date: String? = (messageObject as PFObject) ["Data"] as? String
if messageText != nil {
self.messagesArray.append(messageText!)
}
if descriptionText != nil {
self.descriptionArray.append(descriptionText!)
}
if date != nil {
self.dateArray.append(date!)
}
}
self.MessageTable.reloadData()
}
}
retrieveMessages()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell?()
cell = tableView.dequeueReusableCellWithIdentifier("cell")
Compiti.text = self.messagesArray[indexPath.row]
DataCompiti.text = self.dateArray[indexPath.row]
DescrizioneCompiti.text = self.descriptionArray[indexPath.row]
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "ReUseCell")
}
return cell!
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messagesArray.count
}
}
When I run it, the simulator just returns a bunch of empty cells. How can I do to return the elements?
Remark From your code:
you cannot implement and call the function inside of viewDidLoad(), you implement all functions/methods outside of the life cycle then call inside.
I don't think its a good idea of having three different arrays to contain your data,you should learn struct or class data structures to group your data since you are getting them from the same class.
struct myDataContainer
{
var message:String?
var descriptionText:String?
var date:String?
}
var arrayOfContainers = [myDataContainer]() //<-- this will be your new array
I saw that you had a customize cell where you wanted to have 2 Labels and UITextView.. you should create a subclass of UITableViewCell then group them inside.
class CustomizeCell :UITableViewCell
{
#IBOutlet weak var Compiti: UILabel!
#IBOutlet weak var DescrizioneCompiti: UITextView!
#IBOutlet weak var DataCompiti: UILabel!
} //<--- Subclass of UITableViewCell above
struct myDataContainer
{
var message:String?
var descriptionText:String?
var date:String?
}
class TableViewControllerCompiti: UITableViewController {
var arrayOfContainers = [myDataContainer]() //<-- this will be your new array
override func viewDidLoad()
{
super.viewDidLoad()
retrieveMessages() //<--- call function
}
func retrieveMessages()
{
var objectT = myDataContainer()
let query = PFQuery(className: "Compiti")
query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in
if let remoteObjects = objects
{
for messageObject in remoteObjects
{
let messageText = messageObject["Materia"] as? String
let description = messageObject["Compiti"] as? String
let date = messageObject["Data"] as? String
objectT.message = messageText!
objectT.descriptionText = description!
objectT.date = date!
self.arrayOfContainers.append(objectT)
}
self.tableView.reloadData()
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomizeCell
// as! CustomizeCell technically speaking make sure that we access our customize cell
let data = self.arrayOfContainers[indexPath.row]
cell.Compiti.text = data.message
cell.DataCompiti.text = data.descriptionText
cell.DescrizioneCompiti.text = data.date
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayOfContainers.count
}
}