我正在尝试使用dispatch_group_notify发送HTTP请求,我需要在继续处理之前等待此命令的结果。
以下是以下电话:
self.save(){(response) in
if let result = response as? Bool {
if(result == true){
dispatch_group_notify(self.myGroup!, dispatch_get_main_queue(), {
print("send carnet finished")
let registrationView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("carnetTable") as! CarnetTableViewController
self.navigationController?.pushViewController(registrationView, animated: true)
})
}
}
}
这是发送HTTP命令的函数:
func save(callback: (AnyObject) -> ()){
dispatch_group_enter(self.myGroup)
let p = pickerDataSource[patients.selectedRowInComponent(0)]
let params = "owner=\(User.sharedInstance.email)&patient=\(p)&carnet=\(commentaires.text!)"
let final_url = url_to_request + "?" + params.stringByAddingPercentEncodingForISOLatin1()!
print("URL addCarnet: \(final_url)")
let url:NSURL = NSURL(string: final_url)!
//let session = NSURLSession.sharedSession()
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration,
delegate: self,
delegateQueue:NSOperationQueue.mainQueue())
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.timeoutInterval = 10
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error data")
dispatch_group_leave(self.myGroup)
callback(false)
return
}
var result = NSString(data: data!, encoding:NSASCIIStringEncoding)!
print("result: \(result)")
}
task.resume()
dispatch_group_leave(self.myGroup)
callback(true)
}
我想在打开新的ViewController(CarnetTableViewController)之前确保保存功能已完成(dispatch_group_leave),但我可以看到在dispatch_group结束之前调用了ViewController ...
如何在打开新视图之前确保保存功能的结束?
答案 0 :(得分:1)
你职能的最后三行:
task.resume()
dispatch_group_leave(self.myGroup)
callback(true)
这会导致任务开始,然后立即(在任务完成之前),离开组并调用callback
。
如果您浏览代码,则dispatch_group_enter
和dispatch_group_leave
会出现在相同的范围内,位于同一个队列中,并且在您致电callback()
之前。这意味着他们实际上并没有做任何事情。到达回调时,dispatch_group为空。
如果您遇到错误,我会发现当错误行第二次调用dispatch_group_leave
时会出现问题(因为这是不平衡的)。
你的意思是:
...
var result = NSString(data: data!, encoding:NSASCIIStringEncoding)!
print("result: \(result)")
dispatch_group_leave(self.myGroup)
callback(true)
}
task.resume()