dispatch_semaphore_t在swift 3中

时间:2017-09-06 10:08:49

标签: ios swift3 semaphore dispatch

我在objective C中使用以下代码来处理信号量。

-(void)doSome{
    semaphore = dispatch_semaphore_create(0);

    BaseViewController *baseVC = [[BaseViewController alloc]init];
    if(baseVC.isUserObjectExist){
        [self callLoginWebService:baseVC.userObject.username passwordString:baseVC.userObject.password];
    }else{
        dispatch_semaphore_signal(semaphore);
    }

    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) { //2
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:100]];
    }

}

但是

  

' dispatch_semaphore_t'在Swift中不可用

如何在swift 3中集成信号量?

1 个答案:

答案 0 :(得分:4)

你可以通过

创建
let semaphore = DispatchSemaphore(value: 0)

Learn official document of Apple

或来自其他代码

let url = URL(string: "")
        let semaphore = DispatchSemaphore(value: 0) // 1
        let _ = DownloadPhoto(url: url!) {
            _, error in
            if let error = error {
            }
            semaphore.signal() // 2
        }
        let timeout = DispatchTime.now() + .seconds(5)
        if semaphore.wait(timeout: timeout) == .timedOut { // 3
        }