Chris
Chris

Reputation: 103

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

Upvotes: 8

Views: 8646

Answers (2)

adrgrondin
adrgrondin

Reputation: 668

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)
{
    let uploadProgress = 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)

Upvotes: 19

jatin verma
jatin verma

Reputation: 1

You can use alamofire(for api calling) with swiftyJSON(json parsing) library for uploading JSON. You just have to call a loader before the alamofire api get called and stop the loader when you will get the response.

Upvotes: -6

Related Questions