【问题标题】:Abort an Alamofire download request before it completes在完成之前中止 Alamofire 下载请求
【发布时间】: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。

【问题讨论】:

    标签: swift alamofire


    【解决方案1】:

    Error -999是系统返回的取消错误。这只是意味着正在进行的URLSessionTask 在完成之前被取消。我们在 Alamofire 5 中将其设为显式错误,但仍将其视为错误状态,因此如果您需要单独处理,可以在 response 闭包中进行。

    【讨论】:

    • 我明白了,谢谢你的解释。认为任务没有被取消,mp3 仍然开始播放,即使在 self.request?.cancel() 调用之后。有什么我想念的吗?
    • 就像我说的,在您的response 闭包中,检查响应是否失败,如果失败则不要播放文件。
    • 谢谢,确实有效。我将 self.request?.cancel() 留在了解除操作中并检查了闭包。