简体   繁体   English

取消一个带有特定网址的Alamofire下载请求

[英]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. 我为此问题搜索了不同的解决方案,但是找不到取消具有特定URL字符串的一个请求的任何解决方案。 How can solve this issue. 如何解决这个问题。 Thanks for all reply. 感谢您的答复。

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: 未经测试,但应该可以使用,使用originalRequest (创建任务时的原始请求)或可选的currentRequest (当前正在处理的请求)来查找要取消的特定任务:

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

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: 尽管luiyezheng的回答确实很不错,而且应该做得很好,但开发人员有时却忽略了它(例如,以我为例), Alamofire.download()实际上返回DownloadRequest ,如果需要,可以将其存储在某个地方,稍后再执行cancel() `ed:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM