TableView not displaying data in ViewController: Swift - ios

Everything was working fine when I had it in an entire TableViewController, but because I need to have a dropdown menu I switched over to a basic ViewController to have more flexibility. Haven't been able to display the data since.
I think I have all my bases covered. It is a tableView inside a viewController. Delegate and dataSource are set from the tableView to my viewController. The cell identifier is correctly set to "cell". The data is being pulled and can confirm it is in the collectionsAndArrays object.
Any help would be great, thanks.
edit: added self.collectionTableView!.reloadData() and still not working
import UIKit
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
#IBOutlet weak var collectionTableView: UITableView!
#IBOutlet weak var menuView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
}

Try this
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.items = NSMutableArray(array: self.collectionInfo)
self.collectionTableView.reloadData()
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
}

Related

Swift - table is empty after moving between controllers

I'm updating existing Objective-C app.
There is a structure:
AppDelegate
- creates mainBackgroundView and adding subview with UITabBarController
I have in one "Tab" HistoryViewController:
#objc class HistoryViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let historyTableViewController = HistoryTableViewController()
self.view.addSubview(historyTableViewController.view)
}
}
And HistoryTableViewController:
import UIKit
#objc class HistoryTableViewController: UITableViewController {
// Mark: properties
var historyCalls = [HistoryItem]()
// Mark: private methods
private func loadSimpleHistory() {
let hist1 = HistoryItem(personName: "Test", bottomLine: "text", date: "10:47")
let hist2 = HistoryItem(personName: "Test 2", bottomLine: "text", date: "10:47")
let hist3 = HistoryItem(personName: "Test 3", bottomLine: "text", date: "10:47")
historyCalls += [hist1, hist2, hist3]
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadSimpleHistory()
self.tableView.register(UINib(nibName: "HistoryCallTableViewCell", bundle: nil), forCellReuseIdentifier: "HistoryCallTableViewCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in 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 historyCalls.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "HistoryCallTableViewCell", for: indexPath) as? HistoryCallTableViewCell else {
fatalError("Coulnd't parse table cell!")
}
let historyItem = historyCalls[indexPath.row]
cell.personName.text = historyItem.personName
cell.bottomLine.text = historyItem.bottomLine
cell.date.text = historyItem.date
return cell
}
}
When I open the navigation tab with HistoryViewController for the first time, table appers with data. When I click into the table or switch navTab and then go back, table is not there anymore.
When I switch to another app and then go back, table is there again.
How to fix this?
Thank you
Call data method in viewwillappear and reload the table..
override func viewWillAppear() {
super.viewWillAppear()
self.loadSimpleHistory()
self.tableview.reloadData()
}

appending array via swift 2

i have a problem with appending an array, you can see my code, i checked the problem's line by: self.items.append(....)
the array is not appended and stay empty.
here is my code:
//
// ViewController.swift
// firer
//
// Created by mike matta on 06/01/2016.
// Copyright © 2016 Mikha Matta. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var showdatA: UILabel!
#IBOutlet weak var tableView: UITableView!
var items:[String] = []
var userFNAME:String = ""
var userDOB:String = ""
let textCellIdentifier = "TextCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
///////////
let UsersChannel = Firebase(url: "https://MYFIREBASE.firebaseio.com/users")
UsersChannel.observeEventType(.ChildAdded, withBlock: { snapshot in
if let az = String?((snapshot.value.objectForKey("full_name"))! as! String) {
self.userFNAME = az
}
if let az2 = String?((snapshot.value.objectForKey("dob"))! as! String) {
self.userDOB = az2
}
print("\(self.userFNAME) - \(self.userDOB)")
self.items.append(self.userFNAME) // heeereeee what i am trying to doooooooo
})
// print(self.items)
}
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 items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell
let row = indexPath.row
cell.textLabel?.text = items[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(items[row])
}
}
i tryed to put the array definition inside the viewdidload() it works...but i need it outside it (like my code)..
i tryed to put the array outside the async block too...still not appending....any one ?
I think that your code works !
The question is :
Why do you think that your array is still empty ?
You have to think the order that your instructions are executed.
At this line :
// print(self.items);
Your array is still empty because the closure is not yet called.
Put this line just after the append and you will see.
And, Just add self.tableView.reloadData() after your append and you will be happy :)
(It will say to your tableview to recall the delegate methods (numberOfRowsInSection ...) )

Does not conform to UITableViewDataSource - Parse app

I'm using a UITableView in a ViewController connected to TodayViewController. I want to use data from my Parse database to load into the TableView.
Here is my TodayViewController class:
import UIKit
class TodayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var InfoTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
InfoTableView!.delegate = self
InfoTableView!.dataSource = self
loadParseData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
let query : PFQuery = PFQuery(className: "News")
query.orderByDescending("Headline")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("NewCell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewCell")
}
//Extract values from the PFObject to display in the table cell
if let Headline = object?["Headline"] as? String {
cell?.textLabel?.text = Headline
}
if let Subtitle = object?["SubtitleText"] as? String {
cell?.detailTextLabel?.text = Subtitle
}
return cell
}
This error crops up:
How do I solve the problem? Is there any mistake in the overall structure? Do request for more information if required.
Yes you are not confirm to protocol UITableViewDataSource because you don't have a required method
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
So you need to inherit PFQueryTableViewController to use the methods you want
class TodayViewController: PFQueryTableViewController {
...
}
I think you have implemented all the delegate methods of tableview outside the main class, i mean there will be a open parenthesis { and the close parenthesis should be end of all the methods. try like this
import UIKit
class TodayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var InfoTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
InfoTableView!.delegate = self
InfoTableView!.dataSource = self
loadParseData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
let query : PFQuery = PFQuery(className: "News")
query.orderByDescending("Headline")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("NewCell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewCell")
}
//Extract values from the PFObject to display in the table cell
if let Headline = object?["Headline"] as? String {
cell?.textLabel?.text = Headline
}
if let Subtitle = object?["SubtitleText"] as? String {
cell?.detailTextLabel?.text = Subtitle
}
return cell
}
}
Hope this will help.

Return number field from Parse into Tableview custom cell

I have a tableview controller with a custom Prototype Cell. The cell contains 2 labels. I am trying to return 2 values from a Parse class. One field is called Notes and is a String value. The other field is called CreditAmount and is a number value. I am having difficulty returning the number value (Credit Amount) in my tableview.
Here is code for tableview controller:
import UIKit
import Parse
import Foundation
class TableViewController: UITableViewController {
var note = [String]()
var credit = [NSInteger]()
var refresher: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
updateNotes()
self.refresher = UIRefreshControl()
self.refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refresher.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
}
func updateNotes() {
let query = PFQuery(className: "Paydown")
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]?, error: NSError?) -> Void in
self.note.removeAll(keepCapacity: true)
self.credit.removeAll(keepCapacity: true)
if let objects = objects as? [PFObject] {
for object in objects {
// var noted = object as PFObject
self.note.append(object["Notes"] as! String)
self.credit.append(object["CreditAmount"] as! NSInteger)
}
self.tableView.reloadData()
} else {
//println(error)
}
self.refresher.endRefreshing()
})
}
func refresh() {
updateNotes()
}
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 Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return note.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
myCell.notesLabel.text = note[indexPath.row]
myCell.amountLabel.text = credit[indexPath.row]
return myCell
}
}
Here is the code for my customer cell:
import UIKit
import Parse
class cell: UITableViewCell {
#IBOutlet weak var notesLabel: UILabel!
#IBOutlet weak var amountLabel: 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
}
}
The myCell.amountLabel.text = credit[indexPath.row] causes an error: cannot assign a value of type NSInteger (aka int) to a value of type String?. How do I get the number field to work?
Update
myCell.amountLabel.text = credit[indexPath.row]
To be
myCell.amountLabel.text = "\(credit[indexPath.row])"

ImagesTabViewController' does not conform to protocol 'UITableViewDataSource'

I know this question has been asked a million times, but I can't find a resolution to this specific issue. I'm using Xcode 6.3 beta 4 with Swift 1.2 and since the last update I haven't been able to get a regular UITableView with the supporting datasource and delegate protocols working.
I am getting the above error and "Definition conflicts with previous value" for the numberOfRowsInSection function. At this point I don't know if it's a Swift change or I am missing something. The tableview is connected properly..
Thanks for any help.
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
var namesArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.collectionInfo = DataManager.getUserCollections()
var collectionNames: AnyObject = self.collectionInfo[3]
println(collectionNames)
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
}}
There is a bracket missing and didReceiveMemoryWarning must be overridden. Here is the revised code:
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
var namesArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.collectionInfo = DataManager.getUserCollections()
var collectionNames: AnyObject = self.collectionInfo[3]
println(collectionNames)
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
} // <- Was missing!
// Override!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
}

Resources