title: Cancel URLSession.shared.dataTask
body: <p>my code allows you to upload an image while it is showing the upload progress, each time I press the &quot;Upload&quot; button. Every time I press it, the progress starts at 0% until it ends at 100%.</p>
  <p>The problem is if I press the &quot;Cancel&quot; button, it cancels the upload of the image, but when I try to upload another image, it uploads it correctly but it does not calculate the progress.</p>
  <pre><code>class UploadImage{
       private var task: URLSessionDataTask?
       private var progressTask: Task&lt;AnyObject, Error&gt;?
  
    public func uploadImage() {
      self.task = nil
      
      self.task = URLSession.shared.dataTask(with: request) { data, response, error in
          if let data = data {
              print(String(data: data, encoding: .utf8)!)
          }
          else {
              print(String(describing: error))
              return
          }
      }
      self.task?.resume()
   }
  
   public func cancelUpload(){
      //self.progressTask!.cancel()
      self.task?.cancel()
   }
  
   public func uploadAllFiles() {
      self.progressTask = Task.detached{
          var task2: URLSessionDataTask?
          var value: Double = 0.0
          while(value &lt; 100.0){
              if(self.task != nil){
                  task2 = self.task
                  if(task2!.countOfBytesSent != 0){
                      //This is the progress
                   value = (round((Double(100.0)/Double(task2!.countOfBytesExpectedToSend)) * Double(task2!.countOfBytesSent)*100)/100)
                  }
              }
          }
          return 0 as AnyObject
      }
      self.uploadImage()
   }
  }
  </code></pre>
  <p>My view in swiftUI</p>
  <pre><code>private var upload
  var body: some View {
   Button(action: {
      upload = Upload()
      Task.detached{
         upload.uploadAllFiles()
      }
   }) {
      Text(&quot;Upload&quot;)                   
   }
  
   Button(action: {
      upload.cancelUpload()
   }) {
      Text(&quot;Cancel&quot;)                   
   }
  }
  </code></pre>