How can we wait for HTTP requests to finish?

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

提交回复
热议问题