Home > Software design >  Do I have place upload or download tasks onto a background thread or does Swift do it for me?
Do I have place upload or download tasks onto a background thread or does Swift do it for me?

Time:04-19

I am unsure about the thread/queue control in Swift for HTTP methods.

Working on the part of my app that makes GET requests, as well as POST and others, from a 3rd party server.

From my main UIViewController, I initialize the class with:

let uploadService = UploadService()
lazy var uploadSession: URLSession = {
let configuration = URLSessionConfiguration.default
return URLSession(configuration: configuration, delegate: self, delegateQueue: .main)
}()

Then later on I call it from the same UIViewController, let uploadService = UploadService()

Before I start to add more functionality to the class below I wanted to ask about:

return URLSession(configuration: configuration, delegate: self, delegateQueue: .main)

When the UploadService class calls methods to my UIViewController, Xcode warned me to do it from the main thread/queue, which I do. So my questions is, does Swift automatically move anything HTTP related to the non-main thread/queue so I don't have to worry about it? Because if that's the case, great. But then why ask me to place it in the main thread/queue, as I did up above? (which I did from a tutorial).

Just want to be clear, should I be declaring it the background thread/queue, or does Swift handle that for me regardless of how I declared it up above?

class UploadService  {
    
    var uploadSession = URLSession.shared

    func start(upFile: XFile, script: String, upLoadInvoiceClass: UploadInvoice) {
        var request = upFile.makeUrlReq(upFile: upFile, script: script)
        
        uploadSession.uploadTask(with: request, from: request.httpBody  )
        { (data, response, error) in
            if let response = response {
               upLoadoiceClass.upResp(resp: response)
            }
            
            if let error = error {
                upLoadoiceClass.upErr(error: error)
            }
            
            if let data = data {
                upLoadoiceClass.upData(data: data)

            }
            }.resume()
    }
}

CodePudding user response:

URLSession ALWAYS does network interactions on a background thread. You don't have to worry about that.

The completion handlers/delegate methods are also run on a background thread by default. That lets you do time-consuming processing on the resulting data without tying up the main thread.

Unless you point give your URL session a different delegate Queue when you create it you should wrap any UI code you put in your completion handlers/delegate methods in a call to the main thread.

Alternately, you can create a URLSession and give it a foreground queue in the delegateQueue parameter you pass in the initializer. If you do that then your completion handlers/delegate methods will be run on that foreground queue.

  • Related