DispatchGroup在Swift 3中不起作用 [英] DispatchGroup not working in Swift 3
问题描述
我正在尝试使调度组在我的代码中工作
I am trying to make dispatchgroup work in my code
let dispatchQueue:DispatchQueue = DispatchQueue(label: "com.dispatchgroup", attributes: .concurrent, target: .main)
var dispatchGroup:DispatchGroup = DispatchGroup()
func renewLoginIfRequired()->String{
self.dispatchGroup.enter()
dispatchQueue.async(group:dispatchGroup){
self.authorizeApplication(completionHandler: {
self.dispatchGroup.leave()
})
}
}
self.dispatchGroup.wait() // Stops execution here
return "Login Success"
}
以上代码在self.dispatchGroup.wait()处停止执行. 我在self.authorizeApplication周围尝试了没有dispatchQueue.async(group:dispatchGroup)的相同代码,也没有运气 我不确定我在做什么错.这里要提到的一件事是self.authorizeApplication将在该函数内发出异步Web服务请求
Above code stops execution at self.dispatchGroup.wait(). I have tried the same code without dispatchQueue.async(group:dispatchGroup) around self.authorizeApplication as well with no luck I am not sure what am i doing wrong. One thing to mention here is that self.authorizeApplication will make an async web service request within that function
进一步阐述问题.我将从此方法返回会话令牌(字符串). 这是调用此函数的功能
To elaborate the problem even more. I will be returning a session token (String) from this method. Here is the function which is calling this
func processPOSTRequest(_ urlString : String, isAnAuthReq:Bool = false, requestObject: Data?, onSuccess: @escaping (NSDictionary?, NSError?) -> Void, onFailure: @escaping (Data?, NSError?) -> Void){
let manager = AFHTTPSessionManager()
let url = URL(string: urlString);
var request = URLRequest(url: url!);
if !isAnAuthReq{
let token = self.renewLoginIfRequired() //-- Get new token before processing a webservice request
request.setValue(token, forHTTPHeaderField: "Authorization")
}
print("processing URl : "+urlString)
request.httpMethod="POST";
request.httpBody = requestObject
request.setValue("application/json; charset=utf-8", forHTTPHeaderField:"Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField:"Accept")
let task = manager.dataTask(with: request, uploadProgress: nil, downloadProgress: nil, completionHandler:{ data, response, error in
if(error == nil){
if let responseCode = (data as? HTTPURLResponse)?.statusCode{
if responseCode != 200 || !((response as? [String: Any])?["success"] as? Bool)!{
let errorResponse = NSError()
print("Response received for URL: "+urlString)
onFailure(nil, errorResponse.addItemsToUserInfo(newUserInfo: ["errorCode":String(responseCode)]))
}
else{
onSuccess(response as! NSDictionary?, nil)
}
}
}
else{
onFailure(nil, error as NSError?)
}
})
task.resume()
}
如果我使用通知"或关闭".我怎样才能做到这一点?我都试过了
If i use Notify or closure. How can i do that? I have tried both of them
推荐答案
我不知道authorizeApplication
请求的内容,但是它的回调很可能在主线程中执行,即在主队列.因此,您在同一队列中进入,离开和等待,因此调用self.dispatchGroup.wait()
后就无法到达self.dispatchGroup.leave()
.
I don't know what is under the hood of the authorizeApplication
request, but it's likely that its callback performs in the main thread, that is, in the main queue. So you enter, leave and wait in the same queue, therefore you can't reach the self.dispatchGroup.leave()
after you've invoked self.dispatchGroup.wait()
.
要处理此问题,您需要重新设计异步请求并在后台队列中调用self.dispatchGroup.leave()
.
To handle that you need to redesign the async request and call self.dispatchGroup.leave()
in a background queue.
这篇关于DispatchGroup在Swift 3中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!