Wait until an asynchronous api call is completed - Swift/IOS

谁说我不能喝 提交于 2019-12-03 08:20:30
Anton

Note: You should not do it this way, as it blocks the thread. See Nate's comment above for a better way.

There is a way to wait for an async call to complete using GCD. The code would look like the following

var semaphore = dispatch_semaphore_create(0)

performSomeAsyncTask {
    ...
    dispatch_semaphore_signal(semaphore)
}

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
dispatch_release(semaphore)

Wikipedia has an OK article in case you know nothing about semaphores.

This is the solution in Swift 3. Again this blocks the thread until asynchronous task is complete, so it should be considered only in specific cases.

let semaphore = DispatchSemaphore(value: 0)

performAsyncTask {
    semaphore.signal()
}

// Thread will wait here until async task closure is complete   
semaphore.wait(timeout: DispatchTime.distantFuture)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!