Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple URLSession uploadTask with progress bar

i struggle totally with the URLSession and uploadTask. Actually I just want to upload a json to a Webserver and while the upload is in progress a simple progressbar should be shown. I implemented the approach given by apple: https://developer.apple.com/documentation/foundation/url_loading_system/uploading_data_to_a_website

the upload is working and i get a response.. so far everything is fine but i don't know how i can show a during the upload a progress bar. What I tried is to show a progressbar before i call the method that contains the upload task

startActivityIndicator()

    let jsonPackage = JSONIncident(incident: incident)

    jsonPackage.sendToBackend(completion: {
        message, error in
  //Handle the server response




    })

    self.activityIndicator.stopAnimating()
    UIApplication.shared.endIgnoringInteractionEvents()

I realized that's stupid because the upload task works asynchronious in another thread.

I guess that i have to use Delegates but i don't know in which way. If i implement URLSessionTaskDelegate for example, i have to implement a bunch of functions like isProxy(), isKind(), isMember etc.

Could you please provide me a simple example how to show a progress bar during the uploadtask is working? That would be so greate! Thank you very much regardsChris

like image 638
Chris Avatar asked Aug 07 '18 19:08

Chris


1 Answers

You need to conform to the URLSessionTaskDelegate protocol and call this delegate method:

func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
{
    var uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
}

Then use the uploadProgress variable for your progress bar.

Create your session like this:

var session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
like image 78
adrgrondin Avatar answered Nov 23 '22 07:11

adrgrondin