user7117894
user7117894

Reputation: 21

Swift TableView custom cell data disappears after reloading table in Today widget

I have created a today extension containing tableView with custom cells and populated this table with data from the server. Now whenever the Web Service is called to refresh the data and table data has to be reloaded, the data from table disappears. In short every time i switch from Today panel to Notification panel and back, the data in table is gone. Below is code of my controller.

TodayViewController.swift:

import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var key : [String]=[String]()

    var value: [String]=[String]()


    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }




    override func viewDidLoad() {
        super.viewDidLoad()



        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            print("This is run on the main queue, after the previous code in outer block")
           self.callUrl()
            self.tableView.reloadData()
        })
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(key.count)
        return key.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell=self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as!CustomCell

        cell.key.text=key[indexPath.row]
        cell.value.text=value[indexPath.row]
        cell.setNeedsLayout()
        return cell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    }

    func callUrl(){

           let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                print("Everyone is fine, file downloaded successfully.")
                self.key.removeAll()
                self.value.removeAll()

                do{

                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                    if let stations = json["stations"] as? [[String: AnyObject]] {

                        for station in stations {

                            if let name = station["stationName"] as? String {

                                if let year = station["buildYear"] as? String {


                                    self.key.append(name)
                                    self.value.append(year)
                                print(self.key)
                                }

                            }
                        }

                    }

                }

                catch {
                    print("Error with Json: \(error)")
                }

            }
        }



        task.resume()

    }


    func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            self.callUrl()
            self.tableView.reloadData()
        })

            completionHandler(NCUpdateResult.NewData)
    }

}

Table with data:

Table with data

Table without data:

Table without data

I am new to ios and swift. Any help will great! Thanks.

Upvotes: 1

Views: 758

Answers (1)

Punit
Punit

Reputation: 1340

you should reload your tableview in success block of method callURL().

Upvotes: 0

Related Questions