我试图在for in循环中运行一个函数X次,但是当所有函数返回后,我想运行另一个函数。
当前,我通过将最后一个功能延迟1秒钟来使其工作,但我真的很想让Dispatch Group工作。
我已经遍历各种在线示例和其他问题,但是我尝试的任何方法似乎都不起作用,目前我所知道的代码将不起作用,因为每次for函数中都运行dispatchGroup.leave()时,而不是返回时发送。
我尝试将DispatchGroup代码放入函数(位于另一个文件中),但是我很困惑,但是我认为我已经接近解决方案了。
我还查看了信号量,并在每次循环运行时使用count并增加一个值,但是我一直回到DispatchGroups。
我最后的办法就是问一个问题!
ViewController代码
@IBAction func removeDeviceBtn(_ sender: Any) {
let dispatchGroup = DispatchGroup()
for owner in arrOwnerList {
dispatchGroup.enter()
self.removeDevice(device: self.device, account: owner as! String, completion: self.completed)
dispatchGroup.leave()
}
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
self.removeDeviceFromServer(device: self.device)
self.sendEmail(to:"gordon@example.co.uk", subject:self.device+" has been removed", text:self.device+" has been removed from the server, please check the sim for bar and termination")
})
其他文件中的功能代码作为扩展名
func completed(isSuccess: Bool) {
}
func removeDevice(device: String, account: String, completion: @escaping (Bool) -> Void) {
let dictHeader : [String:String] = ["username":Username,"password":Password]
let dictArray = [device]
WebHelper.requestPUTAPIRemoveDevice(BaseURL+"rootaccount/removedevices/"+account+"?server=MUIR", header: dictHeader, dictArray: dictArray, controllerView: self, success: { (response) in
if response.count == 0 {
DispatchQueue.main.async {
GlobalConstant.showAlertMessage(withOkButtonAndTitle: GlobalConstant.AppName, andMessage: Messages.ServerError, on: self)
}
}
else {
if response.count != 0 {
let isSuccess = true
completion(isSuccess)
}
else{
DispatchQueue.main.async {
GlobalConstant.showAlertMessage(withOkButtonAndTitle: GlobalConstant.AppName, andMessage: Messages.NoDataFound, on: self)
}
}
}
}) { (error) in
DispatchQueue.main.async {
GlobalConstant.showAlertMessage(withOkButtonAndTitle: GlobalConstant.AppName, andMessage: error?.localizedDescription ?? Messages.ServerError, on: self)
}
}
}
WebHelper文件中的代码
class func requestPUTAPIRemoveDevice(_ strURL: String,header: Dictionary<String,String>,dictArray: Array<Any>, controllerView viewController: UIViewController, success: @escaping (_ response: [AnyHashable: Any]) -> Void, failure: @escaping (_ error: Error?) -> Void) {
if GlobalConstant.isReachable() {
DispatchQueue.main.async {
LoadingIndicatorView.sharedInstance.showHUD()
}
let loginString = String(format: "%@:%@", header["username"]!, header["password"]!)
let loginData: Data = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString(options: NSData.Base64EncodingOptions())
let headers = ["Authorization": "Basic "+base64LoginString, "Referer": "http://www.example.com"]
let postData = try? JSONSerialization.data(withJSONObject: dictArray, options: [])
let request = NSMutableURLRequest(url: NSURL(string: strURL)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "PUT"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
DispatchQueue.main.async {
LoadingIndicatorView.sharedInstance.hideHUD()
}
failure(error)
} else {
if let httpResponse = response as? HTTPURLResponse {
print("Server code \(httpResponse.statusCode)")
if httpResponse.statusCode == 200 || httpResponse.statusCode == 208 {
DispatchQueue.main.async {
LoadingIndicatorView.sharedInstance.hideHUD()
}
let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
if (jsonResult is NSDictionary) {
success(jsonResult as! [AnyHashable : Any])
}
else if (jsonResult is NSArray) {
success(["response":jsonResult as! NSArray])
}
else{
success(["response":httpResponse.statusCode])
DispatchQueue.main.async {
}
}
}
else{
DispatchQueue.main.async {
LoadingIndicatorView.sharedInstance.hideHUD()
}
failure(error)
}
}
}
})
dataTask.resume()
}
else {
DispatchQueue.main.async {
LoadingIndicatorView.sharedInstance.hideHUD()
GlobalConstant.showAlertMessage(withOkButtonAndTitle: "", andMessage: "Internet not connected", on: viewController)
}
}
}
最终的解决方案(除了整理各种其他问题)是将success(["response":httpResponse.statusCode])
添加到WebHelper文件中,上面的代码已更正
答案 0 :(得分:2)
将leave
放在完成处理程序中:
for owner in arrOwnerList {
dispatchGroup.enter()
removeDevice(device: device, account: owner as! String) { [weak self] success in
self?.completed(isSuccess: success)
dispatchGroup.leave()
}
}
或者鉴于您实际上并没有在completed
函数中做任何事情,我将其删除:
for owner in arrOwnerList {
dispatchGroup.enter()
removeDevice(device: device, account: owner as! String) { _ in
dispatchGroup.leave()
}
}
我注意到您在removeDevice
中有执行路径,它们没有调用完成处理程序。确保每个执行路径都调用完成处理程序,否则您的调度组将永远不会得到解决。
func removeDevice(device: String, account: String, completion: @escaping (Bool) -> Void) {
let dictHeader = ["username": Username, "password": Password]
let dictArray = [device]
WebHelper.requestPUTAPIRemoveDevice(BaseURL+"rootaccount/removedevices/"+account+"?server=MUIR", header: dictHeader, dictArray: dictArray, controllerView: self, success: { response in
DispatchQueue.main.async {
if response.count == 0 {
GlobalConstant.showAlertMessage(withOkButtonAndTitle: GlobalConstant.AppName, andMessage: Messages.ServerError, on: self)
completion(false)
} else {
completion(true)
}
}
}, failure: { error in
DispatchQueue.main.async {
GlobalConstant.showAlertMessage(withOkButtonAndTitle: GlobalConstant.AppName, andMessage: error?.localizedDescription ?? Messages.ServerError, on: self)
completion(false)
}
})
}
顺便说一句,我不知道“失败”关闭的名称,因此我假设它是failure
,但可以根据您的requestPUTAPIRemoveDevice
方法的要求进行调整。我们通常会在Swift中避免使用多重闭包模式,但是如果您要这样做,我会避免使用尾随的闭包语法。它使第二次关闭的功能意图更加明确。
或者,所有这些都引出了一个问题,为什么requestPUTAPIRemoveDevice
根本就启动了UI更新。我可能会将其放在视图控制器方法中。因此requestPUTAPIRemoveDevice
应该只传回足够的信息,以便removeDeviceBtn
例程知道出现什么错误。对于每个故障显示单独的错误消息的想法也可能是可疑的。 (例如,如果您失去了互联网连接,并试图删除许多设备,您是否真的要显示许多单独的错误消息?)但这不在此问题的范围内。