dispatch_semaphore_t in swift 3

4k Views Asked by At

I am using the below code in objective C to work with semaphore.

-(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]];
    }

}

But

'dispatch_semaphore_t' is unavailable in Swift

How to integrate semaphores in swift 3 ?

1

There are 1 best solutions below

3
On

you can create by

let semaphore = DispatchSemaphore(value: 0)

Learn official document of Apple

OR From other code

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
        }