How can we wait for HTTP requests to finish?

前端 未结 3 1527
孤街浪徒
孤街浪徒 2021-01-15 18:23

Using several answers on SO, we have managed to write and execute a basic HTTP request:

import Foundation

let url:URL = URL(string: \"http://jsonplaceholder         


        
3条回答
  •  走了就别回头了
    2021-01-15 18:59

    The most straight-forward (and built-in) way is probably to use a DispatchSemaphore:

    <...>
    
    let sem = DispatchSemaphore(value: 0)
    
    let task = session.dataTask(with: request as URLRequest) {
        (data, response, error) in
    
        <...>
        sem.signal()
    }
    
    task.resume()
    sem.wait()
    

提交回复
热议问题