简体   繁体   中英

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 without data:

没有数据的表

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

您应该在方法callURL()的成功块中重新加载表视图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM