【发布时间】:2024-01-14 04:53:02
【问题描述】:
我实例化了一个通过 Alamofire 下载远程 mp3 文件的请求。下载完成后会自动播放此文件。如果用户决定在完成之前离开屏幕,我会尝试取消请求。这仅在下载完成时才有效,而如果我在下载过程中取消,它会给我一个 -999 错误代码。
我已经尝试了有关取消 Alamofire 请求的所有方法,但似乎没有任何效果。
func startDownload(audioUrl: String) -> Void {
audioFileURL = self.getSaveFileUrl(fileName: audioUrl)
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
return (self.audioFileURL!, [.removePreviousFile, .createIntermediateDirectories])
}
self.request = Alamofire.download(audioUrl, to: destination).downloadProgress(closure: {(progress) in
// Download in progress
let roundedNum = progress.fractionCompleted*100
let roundedString = String(format: "%.0f", roundedNum)
self.topLabel.text = "\(roundedString)%"
}).response(completionHandler: {(DefaultDownloadResponse) in
// Download completed
self.topLabel.text = "Now playing"
self.playAudio()
})
}
然后当用户退出屏幕时,我触发以下内容:
@IBAction func dismissPlayVC(_ sender: Any) {
self.request?.cancel() // Cancelling the download request when exiting PlayVC
player.pause() // Pause player if audio is playing while exiting PlayVC
if let urlString = audioUrlString {
clearDiskCache(audioUrl: urlString)
}
self.dismiss(animated: true, completion: nil)
}
请求在开始时被实例化,如下所示:
var request: Alamofire.Request?
有什么建议吗?错误代码是-999。
【问题讨论】: