3
非同期機能を使用して同期操作を行うにはどうすればよいですか?非同期コールバックで同期操作を行う方法は?
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> B
予想:A> B> C
私はそうする終了ブロック方法がある知っています。しかし要求は入れ子にされます。
func request(_ myRequestURL: URL, completion: @escaping (_ data: Data?) -> Void) {
// Async function
Alamofire.request(myRequestURL).response { response in
completion(response.data)
}
}
(B){_
でMyClass.shared MyClass.shared.request
における(A){_ MyClass.shared.request .request(C){_ in
}
}
}
可能性のある重複した[チェーン複数Alamofire要求](http://stackoverflow.com/questions/28634995/chain-multiple-alamofire-requests) – kennytm
お使いのキューのシリアル: 'operationQueue.maxConcurrentOperationCount = 1 ' – shallowThought
うんそれはjavascriptの[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)に似ています。どのように私はGCDと甘い方法で行うことができますか? – WeiJay