我的問題很簡單,但經過許多研究和測試後,在繼續流程之前,我沒有成功等待函數結束。如何等待函數調用在Swift結束
例子:
print("Before stuff")
do_stuff {
print("After stuff")
}
func do_stuff(onCompleted:() ->()) {
let postEndpoint: String = "http://localhost:8080/users/1234567890987654"
guard let url = NSURL(string: postEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /users/1234567890987654")
print(error)
return
}
// parse the result as JSON
let user: NSDictionary
do {
user = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
// Means that user does not exist
return
}
print("The user is: " + user.description)
})
task.resume()
onCompleted()
}
如何等待do_stuff第二打印()之前結束了嗎?
感謝您的幫助,我想我錯過了什麼。
托馬斯
隨着代碼的寫入,第二個'print'調用肯定會在'do_stuff'完成執行後執行。函數的實現方式有什麼特別之處嗎? – Cristik
不要等待!回電或通知 – vadian
@Cristik:比方說,在do_stuff中,長操作像REST API調用一樣執行。 – Thomi