Swift wait for closure thread to finish

前端 未结 2 1280
别跟我提以往
别跟我提以往 2021-02-08 13:56

I\'m using a very simple swift project created with SPM where it includes Alamofire.

main.swift:

import Alamofire

Alamofire.request(\"https://google.com         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-08 14:27

    Simplest way to wait for an async task is to use a semaphore:

    let semaphore = DispatchSemaphore(value: 0)
    
    doSomethingAsync {
        semaphore.signal()
    }
    
    semaphore.wait()
    
    // your code will not get here until the async task completes
    

    Alternatively, if you're waiting for multiple tasks, you can use a dispatch group:

    let group = DispatchGroup()
    
    group.enter()
    doAsyncTask1 {
        group.leave()
    }
    
    group.enter()
    doAsyncTask2 {
        group.leave()
    }
    
    group.wait()
    
    // You won't get here until all your tasks are done
    

提交回复
热议问题