简体   繁体   English

异步问题JSON Swift

[英]Asynchronous Issue JSON Swift

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

    if (error != nil) {
        println(error)


    } else {


        let jsonresult = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        var dummyfeed:AnyObject

       //println(jsonresult)
        for var i = 0; i <  jsonresult["feed"]!.count; i++ {

            self.feeds.append([String:String]())

            dummyfeed = jsonresult["feed"]![i] as NSDictionary

           self.feeds[i]["id"] = dummyfeed["id"] as? String
           self.feeds[i]["name"] = dummyfeed["name"] as? String
           self.feeds[i]["status"] = dummyfeed["status"] as? String
           self.feeds[i]["profilePic"] = dummyfeed["profilePic"] as? String
            self.feeds[i]["timeStamp"] = dummyfeed["timeStamp"] as? String
            self.feeds[i]["url"] = dummyfeed["url"] as? String

        }

    }
})
task.resume()

So Feeds is a global variable, so that I display the picture of each entry in Feeds on a table view. 因此, Feeds是一个全局变量,因此我可以在表格视图上显示Feeds中每个条目的图片。 But it's calling asynchronously println(self.feeds) inside the task variable and println(feeds) outside of the task variable are differnent. 但是它异步调用任务变量内的println(self.feeds)和任务变量外的println(feeds)是不同的。 How do I make it synchronously? 如何同步制作?

Do not make it run synchronously. 不要使其同步运行。 Run it asynchronously, but then synchronize the interaction with feeds. 异步运行它,然后将交互与提要同步。 The simplest way to achieve that it to dispatch the updating of the feeds back to the main queue and reloadData for the table view. 实现它的最简单方法是将提要的更新分派回主队列并为表视图重新加载数据。 This eliminates the possibility that you'll be using it from the main queue while it's mutating in the background, but avoids the horrible UX of doing this network request synchronously: 这样就消除了在后台进行突变时您将从主队列中使用它的可能性,但是避免了可怕的UX同步执行此网络请求:

let task = session.dataTaskWithURL(url!) { data, response, error in
    if (error != nil) {
        println(error)
    } else {
        var parseError: NSError?
        if let jsonresult = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: nil) as? NSDictionary {
            if let receivedFeeds = jsonresult["feed"] as? [[String: AnyObject]] {
                dispatch_async(dispatch_get_main_queue()) {
                    self.feeds = [[String: String]]()
                    for receivedFeed in receivedFeeds {
                        var outputFeed = [String : String]()
                        outputFeed["id"] = receivedFeed["id"] as? String
                        outputFeed["name"] = receivedFeed["name"] as? String
                        outputFeed["status"] = receivedFeed["status"] as? String
                        outputFeed["profilePic"] = receivedFeed["profilePic"] as? String
                        outputFeed["timeStamp"] = receivedFeed["timeStamp"] as? String
                        outputFeed["url"] = receivedFeed["url"] as? String
                        self.feeds.append(outputFeed)
                    }
                    self.tableView.reloadData()
                }
            } else {
                println("did not find `feed`")
            }
        } else {
            println("problem parsing JSON: \(parseError)")
        }
    }
}
task.resume()

That should be a little more robust handling errors and employs asynchronous pattern of letting request run asynchronously, but dispatch updating of model object and UI back to the main thread. 那应该是更健壮的处理错误,并采用让请求异步运行的异步模式,但是将模型对象和UI的更新分派回主线程。

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

        if (error != nil) {
            println(error)


        } else {


            let jsonresult = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

            var dummyfeed:AnyObject

           //println(jsonresult)
            for var i = 0; i <  jsonresult["feed"]!.count; i++ {

                self.feeds.append([String:String]())

                dummyfeed = jsonresult["feed"]![i] as NSDictionary
                dispatch_async(dispatch_get_main_queue()) {

                    self.feeds[i]["id"] = dummyfeed["id"] as? String
                    self.feeds[i]["name"] = dummyfeed["name"] as? String
                    self.feeds[i]["status"] = dummyfeed["status"] as? String
                    self.feeds[i]["profilePic"] = dummyfeed["profilePic"] as? String
                    self.feeds[i]["timeStamp"] = dummyfeed["timeStamp"] as? String
                    self.feeds[i]["url"] = dummyfeed["url"] as? String
                }

            }
            self.tableView.reloadData()
        }

    })

        task.resume()

Hey Rob, I did what I think you tell me to do, and feeds is still empty :( 嗨,罗伯,我做了我想你告诉我的事情,但提要仍然是空的:(

I have same problem my code is was working fine, but now, using dataTaskWithURL it didn't return any data, or even error. 我有一个同样的问题,我的代码运行正常,但是现在,使用dataTaskWithURL并没有返回任何数据,甚至没有错误。 I think issue is iOS 8.2 I upgraded. 我认为问题是我升级的iOS 8.2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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