NSUserDefault synchronize on back button swift - ios

I have a problem with my UITableView. I have 3 views with navigation controller. The second one have a table, the third is a search with some values. I want to click on button search (third view) and open second view and update the table. But not update. To work I have to return to first view and open again second view.
Second view code:
class Empresa: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate{
let textCellIdentifier = "cell"
var menu:[[String]] = [[]]
var buscaEmp:BuscadorEmpresa = BuscadorEmpresa()
#IBOutlet weak var tablaVista: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
recuperaEmpresas()
tablaVista.delegate = self
tablaVista.dataSource = self
}
func recuperaEmpresas(){
menu = buscaEmp.getEmpresas()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! CustomTableViewCell
let row = indexPath.row
cell.nombreEmp.text = menu[row][0]
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
recuperaEmpresas()
self.tablaVista.reloadData()
}
As you can see I reload my tableView (tablaVista) on viewWillAppear but don't update.
RecuperaEmpresa() call this method:
func getEmpresas() -> [[String]]{
NSUserDefaults.standardUserDefaults().synchronize()
var array = [[""]]
if((NSUserDefaults.standardUserDefaults().arrayForKey("ARRAYEMPRESA")) != nil){
array = NSUserDefaults.standardUserDefaults().arrayForKey("ARRAYEMPRESA")! as! [[String]]
return array
}
return array }
I was debugging and it's like getEmpresa don't update first time
EDIT:
GetEmpresa not return the last value the first time, but if I print return correct value. The problem must be NSUSERDEFAULT
EDIT WITH IMAGES
EDITED FOR Alessandro Ornano
Finally my tableView reload but I see an instant my last values and change it with news. I use that:
Second view:
let textCellIdentifier = "cell"
var menu:[[String]] = [[]]
//var buscaEmp:BuscadorEmpresa = BuscadorEmpresa()
#IBOutlet weak var tablaVista: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
recuperaEmpresas()
tablaVista.delegate = self
tablaVista.dataSource = self
}
func recuperaEmpresas(){
self.menu = NSUserDefaults.standardUserDefaults().arrayForKey("ARRAYEMPRESA")! as! [[String]]
//self.menu = buscaEmp.getEmpresas()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! CustomTableViewCell
let row = indexPath.row
cell.nombreEmp.text = menu[row][0]
return cell
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
recuperaEmpresas()
viewDidLoad()
self.tablaVista.reloadData()
}
Third view button call this methods:
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
var err: NSError?
do{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
let jsonEmpresas = myJSON["TablaEmp"]!!["item"]
let empresas: [[String: AnyObject]]
if let multipleEmpresas = jsonEmpresas as? [[String: AnyObject]] {
empresas = multipleEmpresas
} else if let singleEmpresa = jsonEmpresas as? [String: AnyObject] {
empresas = [singleEmpresa]
} else {
empresas = []
}
for empresa in empresas{
let zcif = empresa["Zcif"] as? String
let zcccp = empresa["Zcccp"] as? String
let zfax = empresa["Zfax"] as? String
let zdocu = empresa["Zdocu"] as? String
self.arrayEmpresas.append([zcif!, zcccp!, zfax!, zdocu!])
}
NSUserDefaults.standardUserDefaults().setObject(self.arrayEmpresas, forKey:"ARRAYEMPRESA")
NSUserDefaults.standardUserDefaults().synchronize()
}catch { print(error)}
}
task.resume()
And
func back(){
navigationController?.popViewControllerAnimated(true)
}
getMethod:
func getEmpresas() -> [[String]]{
NSUserDefaults.standardUserDefaults().synchronize()
var array = [[""]]
if((NSUserDefaults.standardUserDefaults().arrayForKey("ARRAYEMPRESA")) != nil){
array = NSUserDefaults.standardUserDefaults().arrayForKey("ARRAYEMPRESA")! as! [[String]]
return array
}
return array
}

When you have this kind of issue many times there are involved synchronism between sampling data and UI update. In your code I dont know where you get this data, how long it takes to arrive and how you set this array on NSUserDefaults. So, if you can't see immediatly your UI updates probably you launch reloadData (main thread) too early because there are still operations to the background thread (http server queries, data fetching...)
You can also write a more elegant:
func getEmpresas() -> [String] {
NSUserDefaults.standardUserDefaults().synchronize()
if let array = NSUserDefaults.standardUserDefaults().arrayForKey("ARRAYEMPRESA")! as! [[String]] {
return array
}
return [String]()
}
UPDATE:
I've seen your update code. I want to focus your attention in this method:
func recuperaEmpresas(){
// Are my data ready to read??? who can say to me this in main thread??
menu = buscaEmp.getEmpresas()
}
So you cant call self.tablaVista.reloadData() until you are pretty sure your data can be exists. To do it you can use a completion handler (click me if you want to know how to build it)
func recuperaEmpresas(url: NSURL,completionHandler: CompletionHandler){
callMyNetwork() { //do call and after finish do...
menu = buscaEmp.getEmpresas()
self.tablaVista.reloadData()
}
}

Try to put tableVista.reloadData() in your prepareForSegue or unwindToHome function (whichever you are using to go back to second view). If this is not possible, you can always set a bool var which determines if the view is loaded from the first view or the second view and then reload data accordingly.
Hope this helps. :)

Related

pass data when clicking the cell in mvvm

I need to select the cell from tableview and my code as below:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let vc = OfferDetailViewController(nibName: "OfferDetailViewController", bundle: nil)
let indexPath = (self.tableView.indexPathForSelectedRow)!
let offerViewModel1 = self.offerViewModel.sourceAt(index: indexPath.row)
vc.offerViewModel2 = offerViewModel1
navigationController?.pushViewController(vc, animated: true)
}
I am doing in the mvvm method. I have two screens.
listing the data in the tableview
on selecting the cell from tableview, it must go to other screen. It contains the details.
I have done to list the data. But on clicking I need to pass he pass. How to do?
I can't understanding did it should pass to viewmodel or viewcontroller.
foodviewmodel:-
class foodViewModel: NSObject {
var datasourceModel:foodDataSource
init(withdatasource offerDatasourceModel: foodDataSource) {
datasourceModel = offerDatasourceModel
}
func datafordisplay(atindex indexPath: IndexPath) -> foodModel{
return datasourceModel.dataListArray![indexPath.row]
}
func numberOfRowsInSection(section:Int) -> Int {
return (datasourceModel.dataListArray?.count)!
}
//indexpath.....
// func sourceAt(atindex indexPath: IndexPath) -> foodModel {
// return self.datasourceModel.dataListArray![indexPath.row]
// }
func sourceAt(index :Int) -> foodModel {
return self.datasourceModel.dataListArray![index]
}
}
foodDataSource .swift:-
var dataListArray:Array<foodModel>? = []
init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{
newArray = self.getJsonDataStored4()
}
else{
newArray = array!
}
var datalist:Array<foodModel> = []
for dict in newArray{
let model = foodModel(dictionary: dict)
datalist.append(model!)
}
self.dataListArray = datalist
}
}
typealias dummyDataSource4 = foodDataSource
extension dummyDataSource4{
func getJsonDataStored4() ->Array<Dictionary<String,String>>{
let jsonArray = [["id":"1","name":"Lunch Buffet","price":"Q28","location":"Doha, Qatar","imageurl":"","offertype":"Today's Offer","restaurtantname":"MOMS KITCHEN"],["id":"2","name":"Economy Meal","price":"Q65","location":"Doha, Qatar","imageurl":"","offertype":"Tomorrow's Offer","restaurtantname":"Mr.Shawarma"],["id":"3","name":"Sit-Down Buffet","price":"Q65","location":"Doha, Qatar","imageurl":"","offertype":"Weekend's Offer","restaurtantname":"Maharaja Darbar"],["id":"4","name":"Lunch Buffet","price":"Q28","location":"Doha, Qatar","imageurl":"","offertype":"Today's Offer","restaurtantname":"Shircz Garden"]] as Array<Dictionary<String,String>>
return jsonArray
}
Then i created fooddetailmodel,fooddetaildatasource,fooddetailviewmodel classes.
But i don't know what to pass
i have given the code:-
var offerViewModel2 :QM_OfferModel!
// #IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}

Populate the data saved on core data on a tableView

The code of my first UIViewController looks like this and basically I want to save the data whatever I type on the UITextField and retrieve it and populate on a UITableView. code as below. (I think my issue is in the cellForRow method)
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet weak var textField1: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func nxtbuttonpressed(_ sender: AnyObject) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//Lets save data
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Expenses", into: context)
newUser.setValue(textField1.text, forKey: "expenseName")
do {
try context.save ()
print("data saved successfully")
}catch{
print("There was an error")
}
performSegue(withIdentifier: "ShowNxtVC", sender: nil)
}
}
This is where I retrieve the data that I saved in the above VC (as the code bellow). However even though I can print all the data on the console, only the last data item I saved will populate to the UITableViewCell. How can i overcome this as to populate all the data that I've saved before instead the one that i saved last.
import UIKit
import CoreData
class TableViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var myArray : Array? = []
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest <NSFetchRequestResult> (entityName: "Expenses")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
// check data existance
if results.count>0 {
print(results.count)
for resultGot in results as! [NSManagedObject]{
if let expName = resultGot.value(forKey:"expenseName") as? String{
myArray = [expName]
print("my array is : \(myArray)")
}
}
}
}catch{
print("No Data to load")
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(myArray?.count)
return myArray!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell ()
cell.textLabel?.text = myArray? [indexPath.row] as! String?
return cell
}
}
first off all you have to change this:
myArray = [newValue] because that resets your array with just one value every time it finds a new expense in core data.
var array = [String]()
array = ["hello"]
array = ["joe"]
print(array)
// returns: ["joe"]
use:
myArray.append(newExpense)
and you get:
var array2 = [String]()
array2.append("hello")
array2.append("joe")
print(array2)
// returns: ["hello", "joe"]
After the FOR loop you add:
tableView.reloadData()
Now you should be up and running
There is another thing you should do:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExpCell", for: indexPath)
cell.textLabel?.text = myArray?[indexPath.row] as! String
return cell
}
In your Storyboard you need to put ExpCell as reuse identifier into the TableViewCell. The dequeReusableCell command loads only the cells you can see on your device and reuses those cells after you scrolled them out of sight. This way your app uses much less memory and will be faster.
update table view with data, after myArray = [expName] use
DispatchQueue.main.async { [unowned self] in
self.tableView.reloadData()
}
change the tableview cell for row at index path function that will solve your problem
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier identifier: String,
for indexPath: IndexPath)
if(!cell){
cell = tableView.register(tableViewCellClass,forCellReuseIdentifier identifier: String)
}
return cell
}

Array does not stacking Class object

I am trying to initialize and then append Class object to array through delegate func. Delegate Double comes from button press with some data.
var expensesArray = [SpendedMoneyObject]()
var delegatedDouble:Double = 0.0
func setExpenses(expensesFromMainView: Double) {
delegatedDouble = expensesFromMainView
var aSpendedMoneyObject = SpendedMoneyObject(moneySpent: delegatedDouble)
expensesArray += [aSpendedMoneyObject]
self.tableView.reloadData()
}
Problem here is that I am trying to show array at TableViewCell, but it doesn't showing at all, I guess main problem is that expensesArray value is 1 and it's not stacking but replacing same array with other value. Will be really happy to hear what you think.
Edit:
I tried .append and it still the same also TableView func cellForRowAtIndexPath does not getting called.
class ExpensesTableViewController: UITableViewController, ExpensesEnteredDelegate{
//MARK : Properties
var expensesArray = [SpendedMoneyObject]()
var delegatedDouble:Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
}
func setExpenses(expensesFromMainView: Double) {
delegatedDouble = expensesFromMainView
var aSpendedMoneyObject = SpendedMoneyObject(moneySpent: delegatedDouble)
expensesArray.append(aSpendedMoneyObject)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return expensesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "ExpensesCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ExpensesTableViewCell
print("Iam here")
let expense = expensesArray[indexPath.row]
let fromDoubleToString = "\(expense.moneySpent)"
cell.loadItemsToCell(fromDoubleToString, date: expense.date)
return cell
}
Object class:
class SpendedMoneyObject {
var moneySpent: Double
var currentTime = NSDate().toShortTimeString()
var date: String
init(moneySpent: Double) {
self.date = currentTime
self.moneySpent = moneySpent
}}
Edit: I can now add more than one array by moving new ViewController creation from spendButton func which was creating newVC every time i clicked button. Here are edited code:
protocol ExpensesEnteredDelegate {
func setExpenses(expensesFromMainView: Double)
}
class MainViewController: UIViewController {
#IBOutlet weak var moneyTextField: UITextField!
var delegate: ExpensesEnteredDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Defining ExpensesVC
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newExpensesVC = storyboard.instantiateViewControllerWithIdentifier("ExpensesTableView") as! ExpensesTableViewController
delegate = newExpensesVC
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func spentButton(sender: AnyObject) {
// Delegating expenses Double value
if (delegate != nil) {
let myDouble = Double(moneyTextField.text!)
let expenses: Double = myDouble!
delegate!.setExpenses(expenses)
}
}}
But still array's data does not showing up in a tableView
Try this code example:
let aSpendedMoneyObject = SpendedMoneyObject(moneySpent: delegatedDouble)
expensesArray.append(aSpendedMoneyObject)
Or you can use .extend() method if you are looking to append more elements from a different array to your array.
instead of
expensesArray += [aSpendedMoneyObject]
try
expensesArray.append(aSpendedMoneyObject)

TableViewController does not appear for a few seconds after Transition

I have a tabbarcontroller with four tableviewcontrollers that are connected by navigation controllers. The tableviews are popualted by images and text download from the internet by a XMLParser. When the app loads, after the splash screen, the screen goes black for a few seconds, then the first table view appears. Tab clicks on the other tableviews also lag. How can I display something in place of a black screen or unresponsive interface while the tableview controller's data is downlaoded?
The code of one of the tableviews:
import UIKit
class TopicsTableViewController: UITableViewController, XMLParserDelegate {
var xmlParser : XMLParser!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://sharontalon.com/feed")
xmlParser = XMLParser()
xmlParser.delegate = self
xmlParser.startParsingWithContentsOfURL(url!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: XMLParserDelegate method implementation
func parsingWasFinished() {
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return xmlParser.arrParsedData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("idCell", forIndexPath: indexPath)
let currentDictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String>
let url = currentDictionary["enclosure"]
let data = NSData(contentsOfURL: url!.asNSURL) //make sure your image in this url does exist, otherwise unwrap in a if let check
let description = currentDictionary["description"]
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.textLabel?.text = currentDictionary["title"]
cell.detailTextLabel?.text = String(htmlEncodedString: description!)
cell.detailTextLabel?.numberOfLines = 3;
cell.textLabel?.numberOfLines = 2;
cell.imageView?.image = UIImage(data: data!)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String>
let tutorialLink = dictionary["link"]
let publishDate = dictionary["pubDate"]
let tutorialViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("idTutorialViewController") as! TutorialViewController
tutorialViewController.tutorialURL = NSURL(string: tutorialLink!)
tutorialViewController.publishDate = publishDate
showDetailViewController(tutorialViewController, sender: self)
}
This may be caused by a simple threading issue, give this a shot and if it doesn't work I'll try to help you further:
First move your resource heavy operation to a background thread:
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://sharontalon.com/feed")
xmlParser = XMLParser()
xmlParser.delegate = self
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
self.xmlParser.startParsingWithContentsOfURL(url!)
})
}
Next, move any code that will update the user interface to the foreground thread:
func parsingWasFinished() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
If this doesn't resolve your issue, let me know any I'll remove this answer and rethink your problem.
Reloading table data has to be on the main thread of the table to be renewed immediately.
func parsingWasFinished() {
self.tableView.reloadData()
}
Would be:
func parsingWasFinished() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}

SWIFT: Difficultly displaying data in tableView

I am attempting to display data from Parse onto the following tableView controller. For some reason, the data is not displaying on the tableView (i.e. the rows are blank). I do not think that the data queried from Parse is being appended to the arrays. I am wondering what I'm doing wrong here.
Here's the current output:
I am using a custom prototype cell with identifier "CellTrack" class "TrackTableViewCell" and as shown below:
Here is my code in the TableViewController file:
import UIKit
import Parse
class MusicPlaylistTableViewController: UITableViewController {
var usernames = [String]()
var songs = [String]()
var dates = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
var query = PFQuery(className:"PlaylistData")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects! as? [PFObject] {
self.usernames.removeAll()
self.songs.removeAll()
self.dates.removeAll()
for object in objects {
let username = object["username"] as? String
self.usernames.append(username!)
print("added username")
let track = object["song"] as? String
self.songs.append(track!)
let date = object["createdAt"] as? String
self.dates.append(date!)
self.tableView.reloadData()
}
}
} else {
print(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellTrack", forIndexPath: indexPath) as! TrackTableViewCell
cell.username.text = usernames[indexPath.row]
cell.songTitle.text = songs[indexPath.row]
cell.CreatedOn.text = dates[indexPath.row]
return cell
}
}
And here is my code in the "TrackTableViewCell.swift" class:
import UIKit
class TrackTableViewCell: UITableViewCell {
#IBOutlet weak var songTitle: UILabel!
#IBOutlet weak var username: UILabel!
#IBOutlet weak var CreatedOn: UILabel!
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
}
}
Execute your tableView.reloadData() in main thread.
dispatch_async(dispatch_get_main_queue(), {
self.tableViewCell.reloadData()
})
Try doing a guard let to see if those values are actually coming back as string or not. My guess would be that the value for created at never came back. Try it out and let me know.
guard let username = object["username"] as? String else {
print ("could not get username")
}
self.usernames.append(username)
print("added username")
guard let track = object["song"] as? String else {
print ("could not get song")
return
}
self.songs.append(track)
guard let date = object["createdAt"] as? String else {
print ("could not get createdAt")
return}
self.dates.append(date!)
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell?
Return Value
A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CellTrack", forIndexPath: indexPath) as! TrackTableViewCell
if cell == nil {
// create a new cell here
cell = TrackTableViewCell(...)
}
cell.username.text = usernames[indexPath.row]
cell.songTitle.text = songs[indexPath.row]
cell.CreatedOn.text = dates[indexPath.row]
return cell
}

Resources