Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

ios - Swift UITableView reloadData in a closure

I believe I'm having an issue where my closure is happening on a background thread and my UITableView isn't updating fast enough. I am making a call to a REST service and in my closure i have a tableView.reloadData() call but it takes a few seconds for this to happen. How do I make the data reload faster (perhaps on the main thread?)

REST Query Function - using SwiftyJSON library for Decoding

func asyncFlightsQuery() {
    var url : String = "http://127.0.0.1:5000/flights"
    var request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: url)
    request.HTTPMethod = "GET"

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, networkData: NSData!, error: NSError!) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil


        // Parse with SwiftyJSON
        let json = JSON(data: networkData)

        // Empty out Results array
        self.resultArray = []

        // Populate Results Array
        for (key: String, subJson: JSON) in json["flights"] {
            print ("KEY: (key) ")
            print (subJson["flightId"])
            print ("
")

            self.resultArray.append(subJson)
        }

        print ("Calling reloadData on table..??")
        self.tableView.reloadData()


    })
}

Once self.tableView.reloadData() is called in my debugger

question from:https://stackoverflow.com/questions/26277371/swift-uitableview-reloaddata-in-a-closure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UIKit isn't thread safe. The UI should only be updated from main thread:

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}

Update. In Swift 3 and later use:

DispatchQueue.main.async {
    self.tableView.reloadData()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...