viewView数据源在viewDidLoad()中为空 - Swift [英] tableView data source empty in viewDidLoad() - Swift

查看:94
本文介绍了viewView数据源在viewDidLoad()中为空 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的ViewController代码。 GetRequest中的println打印从HTTP GET请求接收的正确数据。此时,tableData有10个键值对。但是,如果我在viewDidLoad()中调用GetRequest()之后设置了一个断点,则tableData为空并且tableView中不显示任何内容。为什么是这样?我哪里错了?

Below is my ViewController code. The println in GetRequest prints the correct data that it receives from the HTTP GET request. At this point, tableData has 10 key-value pairs. However, if I put a break point after the call to GetRequest() in viewDidLoad(), tableData is empty and nothing is displayed in the tableView. Why is this? Where am I going wrong?

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
    @IBOutlet var tableView: UITableView!
    var tableData: [String:String] = [:]
    let textCellIdentifier = "TextCell"

func GetRequest(urlPath: String)
{
    var LatestWaitTimes: [String:String] = [:]
    let url: NSURL = NSURL(string: urlPath)!
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in

        if error != nil {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }

        var err: NSError?
        var jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err)
        if err != nil {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")
        }

        let json = JSON(jsonResult!)
        let count: Int? = json.array?.count

        if let ct = count {
            for index in 0...ct-1 {
                let name = json[index]["CrossingName"].string
                var wait = json[index]["WaitTime"].stringValue
                if (wait == "-1")
                {
                    wait = "No Info"
                }
                else
                {
                    wait += " min"
                }
                println(name!+": "+wait)
                LatestWaitTimes[json[index]["CrossingName"].stringValue] = wait as String?
            }
        }
        self.tableData = LatestWaitTimes
    })
    task.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    var apiInfo = GetWaitTimes()
    GetRequest(apiInfo.BorderCrossingApi+"?AccessCode="+apiInfo.AccessCode)
    self.tableView.delegate = self
    self.tableView.dataSource = self
    tableView.reloadData()
}

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

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier(self.textCellIdentifier) as! UITableViewCell
    let thisEntry = self.tableData.values.array[indexPath.row]
    cell.textLabel?.text = thisEntry+": "+tableData[thisEntry]!
    return cell
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}


推荐答案

问题是 GetRequest 以异步方式运行。所以你必须在 completionHandler dataTaskWithURL reloadData

The problem is that GetRequest runs asynchronously. So you have to reloadData inside the completionHandler of dataTaskWithURL:

let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in

    // do all of your existing stuff here

    dispatch_async(dispatch_get_main_queue()) {
        self.tableData = LatestWaitTimes
        self.tableView.reloadData()
    }
})
task.resume()

你可以删除来自 viewDidLoad 中的 reloadData

这篇关于viewView数据源在viewDidLoad()中为空 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆