gpt4 book ai didi

ios - 使用 dispatch_group_notify 的快速异步请求不起作用

转载 作者:行者123 更新时间:2023-11-28 16:09:38 25 4
gpt4 key购买 nike

我正在尝试使用 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...

如何确保在打开新 View 之前保存功能结束?

最佳答案

函数的最后三行:

task.resume()
dispatch_group_leave(self.myGroup)
callback(true)

这会导致任务开始,然后您立即(在任务完成之前)离开群组并调用回调

如果您跟踪代码,您的 dispatch_group_enterdispatch_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()

关于ios - 使用 dispatch_group_notify 的快速异步请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39756969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com