How to run synchronically two functions with async operations on iOS using Swift

前端 未结 3 1833
庸人自扰
庸人自扰 2021-02-03 13:12

lets propose this scenario

a method with async network operations

func asyncMethodA() -> String?
{
   result : String?
   Alamofire.manager.request(.P         


        
3条回答
  •  广开言路
    2021-02-03 13:32

    func anAsyncMethod(resultHandler: (result: AnyObject) -> Void) {
        ...        
    }
    
    func anotherAsyncMethod(resultHandler: (result: AnyObject) -> Void) {
        ... 
    }
    
    let operationQueue = NSOperationQueue()
    
    func performWithCompletionHandler(completion: (AnyObject?, AnyObject?) -> Void) {
            var resultOfOperation1: AnyObject?
            var resultOfOperation2: AnyObject?
    
            let operation1 = NSBlockOperation {
                    let dispatchGroup = dispatch_group_create()
                    dispatch_group_enter(dispatchGroup)
                    self.anAsyncMethod {
                            result in
                            resultOfOperation1 = result
                            dispatch_group_leave(dispatchGroup)
                    }
                    // wait until anAsyncMethod is completed
                    dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
            }
    
            let operation2 = NSBlockOperation {
                    let dispatchGroup = dispatch_group_create()
                    dispatch_group_enter(dispatchGroup)
                    self.anotherAsyncMethod {
                            result in
                            resultOfOperation2 = result
                            dispatch_group_leave(dispatchGroup)
                    }
                    // wait until anotherAsyncMethod is completed
                    dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
            }
    
            let completionOperation = NSBlockOperation {
                    // send all results to completion callback
                    completion(resultOfOperation1, resultOfOperation2)
            }
    
            // configuring interoperation dependencies
            operation2.addDependency(operation1)
            completionOperation.addDependency(operation2)
    
            operationQueue.addOperations([operation1, operation2, completionOperation], waitUntilFinished: false)
    }
    

提交回复
热议问题