在下面的代码中,我有一个调用任务来获取学生位置的函数。执行任务初始化之前的行,但任务本身似乎没有执行。在我看来,即使在任务完成之前,函数的下一行也会被执行。所以我尝试了两件事
有人可以解释这是否是另一个线程以及如何让函数等待该线程完成?我很想知道是否有办法使这项工作,以及是否有更好的方法来做到这一点。非常感谢。
func getStudentLocation(completionHandler: (studentDictionary: NSDictionary) -> ()) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://parse.udacity.com/parse/classes/StudentLocation")!)
request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
let session = NSURLSession.sharedSession()
print("starting task")
let task = session.dataTaskWithRequest(request) { (data, response, error) in
print("getStudentLocation in task: \(error) \(response)")
if error != nil { // Handle error...
print(" error in get student location: \(error)")
return
}
let parsedResult: AnyObject
do {
parsedResult = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
}
catch {
return
}
self.studentDictionary = parsedResult["results"] as? [String: AnyObject]
// completionHandler(studentDictionary: self.studentDictionary!)
print("STudent Dictonary: \(self.studentDictionary)")
}
task.resume()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
getStudentLocation{
studentDictionary in
//studentDictionary.count
print("Count: \(studentDictionary.count)")
}
return studentDictionary!.count
}
答案 0 :(得分:0)
The dataTaskWithRequest()
runs in background. That's why your function returns immediately after task.resume()
.
To display the downloaded data in you tableView
, you have to reload its data at the end of the task
's completion handler. Right after self.studentDictionary = parsedResult["results"] as? [String: AnyObject]