A solution to track a batch of HTTP requests in swift 3.0

后端 未结 3 580
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 13:10

I am using swift 3.0 running under iOS 10.0 and I want to craft some code that fires when a batch condition is met.

for i in 0 ..< rex {
   async code, disapp         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 13:58

    While OperationQueue (aka NSOperationQueue) is a good choice in many cases, it's not suitable for your use case. The problem is that URL requests are called asynchronously. Your NSOperation will finish before you get a response from the webservice.

    Use DispatchGroup instead

    let group = DispatchGroup()
    
    // We need to dispatch to a background queue because we have 
    // to wait for the response from the webservice
    DispatchQueue.global(qos: .utility).async {
        for i in 0 ..< rex {
            group.enter()          // signal that you are starting a new task
            URLSession.shared.dataTask(with: urls[i]) { data, response, error in
                // handle your response
                // ....
                group.leave()      // signal that you are done with the task
            }.resume()
        }
    
        group.wait()               // don't ever call wait() on the main queue
    
        // Now all requests are complete
    }
    

提交回复
热议问题