ava
ava

Reputation: 1176

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.

Upvotes: 0

Views: 1904

Answers (2)

Fyodor Volchyok
Fyodor Volchyok

Reputation: 5673

Though luiyezheng's answer is really good and should do the job it is sometimes overlooked by developers (by me for example) that Alamofire.download() actually returns DownloadRequest which could be stored somewhere if needed and later cancel() `ed:

let request = Alamofire.download("http://test.com/file.png")
r.cancel()

Upvotes: 1

ilovecomputer
ilovecomputer

Reputation: 4708

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()
        }
    }
}

Upvotes: 5

Related Questions