DispatchGroup多次返回

时间:2016-09-22 04:42:54

标签: ios swift grand-central-dispatch swift3 dispatch-async

我用于进行concurrent API调用的代码。不知怎的,这种方法多次返回。我在没有DispatchGroup的情况下进行了测试,它按预期工作。帮助我找出它多次呼叫的原因。

我的代码段:

     func makeConcurrentCallForUpdating(_ parent: Parent,
                        completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) 
        let fetchGroup = DispatchGroup()
        let queue = DispatchQueue.global(qos: .default)
        let endPoints = [.email, .others ]
        DispatchQueue.concurrentPerform(iterations: endPoints.count) { (index) in
           let enumType = endPoints[index]
           switch enumType {
           case .email:
               updateEmail(parent, fetchGroup: fetchGroup, completionBlock: completionBlock)
           case .others:
               update(parent, fetchGroup: fetchGroup, completionBlock: completionBlock)
           default:
            break
         }
       } 

        fetchGroup.notify(queue: queue) {
           if self.endPoints.count > 0 {
              completionBlock(false, error)
           } else {
            self.saveUpdated(parent, completionBlock: completionBlock)
         }
        }
   }

   #MARK: EMAIL CALL
       fileprivate func updateEmail(_ parent: Parent,
                             fetchGroup: DispatchGroup,
                             completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) {
        fetchGroup.enter()
        updateEmail(parent: parent) { (success, error) in
             fetchGroup.leave()
        }
     } 

1 个答案:

答案 0 :(得分:0)

在群组中的任何任务enter()之前,您需要leave()所有已发送的任务。

fetchGroup.enter()

之前移动DispatchQueue.concurrentPerform(...
    let endPoints = [.email, .others ]
    endPoints.forEach {_ in fetchGroup.enter()} //<- add this line
    DispatchQueue.concurrentPerform(iterations: endPoints.count) { (index) in

并删除每项任务中的fetchGroup.enter()

fileprivate func updateEmail(_ parent: Parent,
                         fetchGroup: DispatchGroup,
                         completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) {
    //fetchGroup.enter() //<- remove this line, in your `update(...)` as well
    updateEmail(parent: parent) { (success, error) in
         fetchGroup.leave()
    }
} 

请尝试。