reloadData does not work after fetching data from get method - ios

I have a table and I got my data from a GET method. After I get the data, I would like to use the reloadData function, but it doesn't work and my table does not show anything.
import SwiftyJSON
class NewsTableViewController: UITableViewController {
var ids = [String]()
var titles = [String]()
var descriptions = [String]()
var images = [String]()
var links = [String]()
var dates = [String]()
#IBOutlet var table_news: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table_news.delegate = self
getNews()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
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 self.ids.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:NewsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "news_cell") as! NewsTableViewCell
cell.lbl_date.text = self.dates[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func getNews() {
RestApiManager.sharedInstance.getNews { (json: JSON) in
if let results = json.array {
for entry in results {
self.ids.append(entry["id"].string!)
self.titles.append(entry["title"].string!) self.descriptions.append(entry["description"].string!)
self.links.append(entry["link"].string!)
self.dates.append(entry["date"].string!)
}
DispatchQueue.main.async{
//print(self.ids.count) it shows 16
self.table_news.reloadData()
}
}
}
}
}

Aren't you returning 0 from numberOfRowsInSection: ? Then, how can the table show anything? :)

Related

Why are the changes made in Xcode Storyboard not getting reflected on Simulator / Device?

I've designed a custom tableview using the storyboard. When app runs on simulator or iphone, the changes does not show up. It still displays last version of the tableview, which does not have Static Cells.
I've tried deleting /Users/xxx/Library/Developer/Xcode/DerivedData directory, cleaning build folder, deleting app on the iPhone and running again, restarting iPhone. Nothing works.
Storyboard version
What shows on device
Here is the code:
import UIKit
class NewDebtViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
let saveText = NSLocalizedString("Save", comment: "Save")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: saveText, style: .done, target: self, action: #selector(saveDebt))
}
//Function to go back
#objc func saveDebt(){
//Here the code for saving the New Debt
//print("Back Button Clicked")
_ = navigationController?.popViewController(animated: true)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
What else to check or do?
Runtime Hierarchy
Solved. Although I'm designing in the Storyboard the delegate code in the class where returning 0 for the number of rows so logically there were no rows in the iPhone:
This is the evil code which was commented for the problem to be solved.
// 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 4
}
This is a screenshot for the runtime:
iPhone Runtime

How to save reorder of rows in TableView with Swift

I search already a few days to the answer on the question how can I save the reorder TableView with Swift? So many tutorials on the internet show how to reorder but not how to save with UserDefaults.
This is my code right now. What do I wrong?
Please can you help me to the solution? Thank you very much.
import UIKit
class soundboardTableViewController: UITableViewController {
var list = ["January","February","March","April","May","June", "July","August","September","October","November", "December"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem
let blockItems = UserDefaults.standard.object(forKey:"soundboard")
if(blockItems != nil) {
list = blockItems as! [String]
}
}
// 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 list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = list[indexPath.row]
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
/* Override to support editing the table view.*/
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
list.remove(at: indexPath.row)
UserDefaults.standard.set(self.list, forKey:"soundboard")
UserDefaults.standard.synchronize()
tableView.reloadData()
}
}
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt indexPath: IndexPath, to: IndexPath) {
let itemToMove = list[indexPath.row]
list.remove(at: indexPath.row)
list.insert(itemToMove, at: indexPath.row)
UserDefaults.standard.set(self.list, forKey:"soundboard")
UserDefaults.standard.synchronize()
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if(self.isEditing) {
}
}
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
Your code in tableView(_:moveRowAt:to:) has some errors. You should change it to:
override func tableView(_ tableView: UITableView, moveRowAt indexPath: IndexPath, to: IndexPath) {
let itemToMove = list[indexPath.row]
list.remove(at: indexPath.row)
list.insert(itemToMove, at: to.row)
UserDefaults.standard.set(self.list, forKey:"soundboard")
}
Notice that I removed UserDefaults.standard.synchronize(). You should remove it from your other methods as well, since it is kind of a non-sense in this case. I have also changed list.insert(itemToMove, at: indexPath.row) to list.insert(itemToMove, at: to.row), because you need to place it to the "destination" index, and not put it back from where you removed it.
The rest of your code seems fine. It should be working once you perform these changes.

Update a table in the detailview of a uisplitviewcontroller

So I have a UISplitViewController and in the DetailView I have a UITableView.
What I want to do is take the selected cell from the root view controller and append it to the string which is populating my tableview in the detail view controller. I can append with selection very easily but I need help with is the updating part.
What's supposed to happen is when you click the cell, it appends the value in the cell to the global variable main.BoatManifest, and then update the table. I just don't know how to do that.
Here's some code:
import UIKit
class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, FullListCellDelegate {
#IBOutlet weak var tableView: UITableView!
func updateName(sender: FullListCell, detVC: DetailViewController) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return main.BoatManifest.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Configure the cell...
cell.textLabel?.text = main.BoatManifest[indexPath.row]
return cell
}
}
struct Main {
var BoatManifest: [String] = []
}
var main = Main(BoatManifest: [" "])
This is the code for my detail view and the struct Main on the bottom is just a global variable. My MainView code is this:
import UIKit
protocol NameSelectionDelegate: class {
func nameSelected()
}
class MasterViewController: UITableViewController {
var Names: [String] = ["John", "Mark", "Paul", "Jeremy"]
override func viewDidLoad() {
super.viewDidLoad()
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
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 Names.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = Names[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
main.BoatManifest.append(Names[indexPath.row])
NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
}
func loadList(){
//load data here
self.tableView.reloadData()
}
}
I attempted to use a UISplitViewController tutorial to figure it out but it didn't have the tableview in the detail view controller. I need to send a message when I select the cell to the detail tableview and have it update with the appended text.
Thanks for your help.

how handle click cell in UITableViewController

I would like to handle click each cell in my controller but my log doesn't show anything !
class RightMenuController: UITableViewController {
let row_items = ["دسته بندی", "ثبت نام/ورود"]
override func viewDidLoad() {
navigationController?.navigationBar.isHidden = true
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
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 row_items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
cell.textLabel?.text = row_items[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(self.row_items[indexPath.row]) // not print anything
}
}
Try this instead of your didSelectRow-method:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.row_items[indexPath.row])
}
The "method signature" (function name) that you are using for the didSelect method is incorrect. What you have listed in your current implementation is the "Swift 2 Version". You might note the way that the argument labels are separated to make the functions a bit more readable like in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
This same renaming style should be applied to didSelectRowAtIndexPath. Here is the full code you can use to test this out in a playground.
import UIKit
class RightMenuController: UITableViewController {
let row_items = ["دسته بندی", "ثبت نام/ورود"]
override func viewDidLoad() {
// We must register a cell manually since there is no storyboard
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "LabelCell")
navigationController?.navigationBar.isHidden = true
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return row_items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
cell.textLabel?.text = row_items[indexPath.row]
return cell
}
// Old Swift 2 method signature
//func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.row_items[indexPath.row]) // not print anything
}
}
// Create the ViewController
let right = RightMenuController(style: .plain)
// Ask the Playground to show your ViewController in the Assistant (2 rings - Right side view)
import PlaygroundSupport
PlaygroundPage.current.liveView = right

Swift Xcode6 UITableView Prototype Cell

I'm doing a project with a UITableView, but I don't know how to add data to it.
Now I'm building my first view, but something is going wrong. Can somebody help me?
Here is the code:
import UIKit
class WorkersListTableViewController: UITableViewController {
var numOfWorkersNames = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
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 {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return numOfWorkersNames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("WorkersCell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell. NameOfTheWorkerLabel.text = numOfWorkersNames[indexPath.row] as String
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
Now the Workers Cell:
class WorkersCellTableViewCell: UITableViewCell {
#IBOutlet weak var NameOfTheWorkerLabel: 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
}
}
Please specify what is the problem and add what data to the tableView
If the problem is that there is only a blank view when app launched, you should add some Strings to numOfWorkersNames
for example: var numOfWorkersNames = ["worker1","worker2","worker3"]
then numberOfRowsInSection will get the array count which is 3, and cellForRowAtIndexPath can get its content from numOfWorkdersNames array

Resources