Search code examples
iosswiftalamofire

cancel one Alamofire download request with a specific url


I have table view that download video file for each cell. Here is my code for downloading video file.

 func beginItemDownload(id:String,url:String,selectRow:Int) {

    let pathComponent = "pack\(self.packID)-\(selectRow + 1).mp4"

    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
      let directoryURL: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
      let folderPath: URL = directoryURL.appendingPathComponent("Downloads", isDirectory: true)
      let fileURL: URL = folderPath.appendingPathComponent(pathComponent)
      return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }
    let url = URL(string:url)

    Alamofire.download(
      url!,
      method: .get,
      parameters: nil,
      encoding: JSONEncoding.default,
      headers: nil,
      to: destination).downloadProgress(closure: { (progress) in
        DispatchQueue.main.async {

          if progress.fractionCompleted < 1 {

             print(Float(progress.fractionCompleted))

          }

          if progress.fractionCompleted == 1 {
            print("Completed")
          }
        }

      }).response(completionHandler: { (defaultDownloadResponse) in

        if let destinationUrl = defaultDownloadResponse.destinationURL  {
          DispatchQueue.main.async {

                    print("destination url -****",destinationUrl.absoluteString)

          }
        }
        if let error = defaultDownloadResponse.error {
          debugPrint("Download Failed with error - \(error)")         
          return
        }
      })
  }

When tapping download button for each tableview cell I can download video file and assign progress value for each cell. But now I want to cancel download request for this cell when tapping on cancel button in each cell, . I search different solution for this issue but I can't find any solution for cancelling one request with a specific url string. How can solve this issue. Thanks for all reply.


Solution

  • Not tested but should work, use originalRequest(which is the original request when the task was created) or optionally currentRequest(which is the request currently being handled) to locate the specific task you want cancel:

    func cancelSpecificTask(byUrl url:URL) {
        Alamofire.SessionManager.default.session.getAllTasks{sessionTasks in
            for task in sessionTasks {
                if task.originalRequest?.url == url {
                    task.cancel()
                }
            }
    
        }
    }
    

    Or only cancel download task:

    func cancelSepcificDownloadTask(byUrl url:URL) {
        let sessionManager = Alamofire.SessionManager.default 
        sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in 
        for task in downloadTasks {
                if task.originalRequest?.url == url {
                task.cancel()
            }
        }
    }