在完成之前中止Alamofire下载请求

时间:2019-07-18 21:00:51

标签: swift alamofire

我实例化了一个通过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。

1 个答案:

答案 0 :(得分:1)

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

相关问题