我正在尝试在我的代码中使调度组工作
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()执行。 我没有使用dispatchQueue.async(group:dispatchGroup)在self.authorizeApplication周围尝试相同的代码,但没有运气 我不知道我做错了什么。这里要提到的一件事是self.authorizeApplication将在该函数中发出异步Web服务请求
编辑1:
更详细地阐述问题。我将从此方法返回一个会话令牌(String)。 这是调用此
的函数 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()
}
如果我使用Notify或关闭。我怎样才能做到这一点?我试过了两个
答案 0 :(得分:1)
我不知道authorizeApplication
请求的内幕是什么,但它的回调可能在主线程中执行,即在主队列中执行。因此,您可以在同一个队列中输入,离开和等待,因此在您调用self.dispatchGroup.leave()
后,您无法访问self.dispatchGroup.wait()
。
要处理您需要重新设计异步请求并在后台队列中调用self.dispatchGroup.leave()
。