How can we wait for HTTP requests to finish?

前端 未结 3 1528
孤街浪徒
孤街浪徒 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:56

    Using CwUtils by Matt Gallagher, I implemented a simple CountdownLatch which does the job:

    import Foundation
    import CwlUtils
    
    <...>
    
    let task = session.dataTask(with: request as URLRequest) {
        (data, response, error) in
    
        <...>
        latch.countDown()
    }
    
    task.resume()
    latch.await()
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-01-15 19:14

    Active waiting seems to be the only way on the GCD. Using standard library material, this is what works:

    import Foundation
    
    <...>
    
    var done = false
    
    let task = session.dataTask(with: request as URLRequest) {
        (data, response, error) in
    
        <...>
        done = true
    }
    
    task.resume()
    
    repeat {
        RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
    } while !done
    
    0 讨论(0)
提交回复
热议问题