带有UITableView的标签需要很长时间才能加载

时间:2015-01-12 06:03:06

标签: ios uitableview swift

我有一个包含UITableView的标签。 UITableView从服务器加载JSON。以下是viewDidLoad()中的一些行:

// Register the UITableViewCell class with the tableView
        self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
        var tblView =  UIView(frame: CGRectZero)
        tableView.tableFooterView = tblView
        tableView.backgroundColor = UIColor.clearColor()

        startConnection()

这是我的startConnection()

func startConnection() {
        let url = NSURL(string: "some correct URL")
        var request = NSURLRequest(URL: url!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        if data != nil {
            var json = JSON(data: data!)

            if let jsonArray = json.arrayValue {
                for jsonDict in jsonArray {
                    var pageName: String? = jsonDict["title"].stringValue

                    //some code

                }
            }
            activityIndicator.stopAnimating()
        } else {
            println("No data")
            activityIndicator.stopAnimating()
            var alert = UIAlertController(title: "No data", message: "No data received", preferredStyle: UIAlertControllerStyle.Alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in

            }
            alert.addAction(cancelAction)

            let OKAction = UIAlertAction(title: "Retry", style: .Default) { (action) in
                self.startConnection()
            }
            alert.addAction(OKAction)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

第一次加载后,标签会在点击时显示。我在想是否导致滞后的NSURLConnection.sendSynchronousRequest。有什么建议和意见吗?我真的不知道如何使用sendAsynchronousRequest = /请帮忙。谢谢! = d

2 个答案:

答案 0 :(得分:1)

你可以这样做:

let url:NSURL = NSURL(string:"some url")
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    /* Your code */
})

答案 1 :(得分:1)

虽然有几种方法可以从网站获取数据,但重要的是您使用dispatch_async(dispatch_get_main_queue()) {}在主线程上执行UI更新。这是因为NSURLSession.dataTaskWithURLNSURLConnection.sendAsynchronousRequest() {}等URL任务在后台线程上执行,因此如果您不在主线程上明确更新UI,则通常会遇到延迟。这是一个简单的请求:

func fetchJSON(sender: AnyObject?) {

    let session = NSURLSession.sharedSession()
    let url: NSURL! = NSURL(string: "www.someurl.com")

    session.dataTaskWithURL(url) { (data, response, error)  in

        var rawJSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil)

        if let result = rawJSON as? [[String: AnyObject]] {
            dispatch_async(dispatch_get_main_queue()) {
                // Update your UI here ie. tableView.reloadData()
            }
        }
    }.resume()
}