如何使用异步回调进行同步操作?

时间:2017-04-13 09:34:06

标签: ios swift

如何使用异步函数进行同步操作?

class MyClass {
    static let shared = MyClass()
    let operationQueue = OperationQueue()
    let dispatchGroup  = DispatchGroup()

    func request(_ myRequestURL: URL) {
        operationQueue.addOperation {
            self.dispatchGroup.enter()
            // Async function
            Alamofire.request(myRequestURL).response { response in
                print(response.request)
                self.dispatchGroup.leave()
            }

            self.dispatchGroup.wait(timeout: .distantFuture)
        }
    }
}
  

MyClass.shared.request(A)
    MyClass.shared.request(B)
    MyClass.shared.request(C)

    输出:C> A>乙
    预期:A> B> ç

我知道有一个完成块方法可以这样做。但请求将嵌套。

func request(_ myRequestURL: URL, completion: @escaping (_ data: Data?) -> Void) {
    // Async function
    Alamofire.request(myRequestURL).response { response in
        completion(response.data)
    }
}
  

MyClass.shared.request(A){_ in     MyClass.shared.request(B){_ in     MyClass.shared.request(C){_ in   }   }     }

1 个答案:

答案 0 :(得分:8)

使用DispatchQueue代替我。

class MyClass {
    static let shared = MyClass()
    let dispatchQueue = DispatchQueue(label: "ALAMOFIRE_REQUEST")
    let dispatchGroup  = DispatchGroup()

    func request(_ myRequestURL: URL) {
        dispatchQueue.async {
            self.dispatchGroup.enter()
            // Async function
            Alamofire.request(myRequestURL).response { response in
                print(response.request)
                self.dispatchGroup.leave()
            }

            self.dispatchGroup.wait(timeout: .distantFuture)
        }
    }
}