重新加载Today小部件中的表后,Swift TableView自定义单元格数据消失

时间:2016-11-05 05:42:53

标签: ios swift uitableview ios9-today-widget

我创建了一个包含自定义单元格的tableView的今天扩展,并使用服务器中的数据填充此表。现在,每当调用Web Service刷新数据并且必须重新加载表数据时,表中的数据就会消失。总之,每当我从“今日”面板切换到“通知”面板并返回时,表格中的数据都将消失。下面是我的控制器的代码。

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

我是ios和swift的新手。任何帮助都会很棒!感谢。

1 个答案:

答案 0 :(得分:0)

你应该在方法callURL()的成功块中重新加载你的tableview。

相关问题