下载文件时关闭网络连接时,可以捕获错误

发布于 2025-01-23 07:25:38 字数 2549 浏览 4 评论 0原文

我正在尝试使用urlsession从服务器下载.mp3文件。它还可以在后台工作。这是我声明的变量。

var urlSession: URLSession?
var sessionTask: URLSessionDownloadTask?
var resumeData: Data?

这就是我初始化urlsession的方式。

let config = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")
config.networkServiceType = .background
urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)

要下载,我正在使用urlsessiondownloadtask。我还实施了暂停/简历功能。这是代码。

func startDownload(with url: String) {
    sessionTask = urlSession?.downloadTask(with: URL(string: url)!)
    sessionTask?.resume()
}

func cancelDownload() {
    sessionTask?.cancel()
}

func pauseDownload() {
    sessionTask?.cancel(byProducingResumeData: { (data) in
        self.resumeData = data
    })
}

func resumeDownload(url: String) {
    if let resumeData = self.resumeData {
        sessionTask = urlSession?.downloadTask(withResumeData: resumeData)
    } else {
        sessionTask = urlSession?.downloadTask(with: URL(string: url)!)
    }
    sessionTask?.resume()
}

由于我已经在后台下载了下载,因此要获得成功,失败和下载进度,我已确认urlsessiondowndowndowndolloaddelegate方法。

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)

即使在后台下载文件时,一切似乎都很好。我在委托方法中获得了下载的成功,失败和进度。

但是问题是,如果我在下载文件的中间关闭网络连接,我会在控制台中获得一些错误日志。但是上述委托方法均未调用。这是日志,

Task <0B34AE9E-0A46-4E78-8C90-7353CDC34929>.<10> finished with error [-1020] Error Domain=NSURLErrorDomain Code=-1020 "A data connection is not currently allowed." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x2817b40c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1020 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <0B34AE9E-0A46-4E78-8C90-7353CDC34929>.<10>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <0B34AE9E-0A46-4E78-8C90-7353CDC34929>.<10>"
), NSLocalizedDescription=A data connection is not currently allowed.

我该如何获取错误响应以向用户显示您丢失网络连接的内容?

我已经搜索了它,但没有找到解决方案。如果这是一个重复的问题,请原谅我。谢谢。

I am trying to download .mp3 file from server using using URLSession. It also works in background. Here is the variables i have declared.

var urlSession: URLSession?
var sessionTask: URLSessionDownloadTask?
var resumeData: Data?

This is how i initialised the URLSession.

let config = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")
config.networkServiceType = .background
urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)

To download i am using URLSessionDownloadTask. I have also implemented pause/resume functionality. Here is the code.

func startDownload(with url: String) {
    sessionTask = urlSession?.downloadTask(with: URL(string: url)!)
    sessionTask?.resume()
}

func cancelDownload() {
    sessionTask?.cancel()
}

func pauseDownload() {
    sessionTask?.cancel(byProducingResumeData: { (data) in
        self.resumeData = data
    })
}

func resumeDownload(url: String) {
    if let resumeData = self.resumeData {
        sessionTask = urlSession?.downloadTask(withResumeData: resumeData)
    } else {
        sessionTask = urlSession?.downloadTask(with: URL(string: url)!)
    }
    sessionTask?.resume()
}

As i have enabled download in background, to receive success, failure and progress of download i have confirmed URLSessionDownloadDelegate methods.

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)

Everything seems fine when i download a file even in background. I have got the success, failure and progress of the download in delegate methods.

But the problem is if i turn off network connection at the middle of downloading a file, i get some error logs in console. But none of the above delegate methods are called. Here is the logs

Task <0B34AE9E-0A46-4E78-8C90-7353CDC34929>.<10> finished with error [-1020] Error Domain=NSURLErrorDomain Code=-1020 "A data connection is not currently allowed." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x2817b40c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1020 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <0B34AE9E-0A46-4E78-8C90-7353CDC34929>.<10>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <0B34AE9E-0A46-4E78-8C90-7353CDC34929>.<10>"
), NSLocalizedDescription=A data connection is not currently allowed.

How can i get the error response to show the user that you have lost your network connection?

I have searched for it but didn't find the solution. Pardon me if it's a duplicate question. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过度放纵 2025-01-30 07:25:38

要返回错误,您需要使用具有 plotectionhandler`的downloadtask的替代功能,

self.urlSsn?.downloadTask(with: MyURLRequest, completionHandler: { data, response, error -> Void in
    if let error = error {
        print("\(error.localizedDescription)")
        // This should print "A data connection is not currently allowed."
    }
}

也可以用于downloadtask(withResumedata)

如果要比较特定的错误代码(示例中的错误代码-1020)。您可以执行以下操作:

if let error = error {
    let e = error! as NSError
    switch e.code {
    case NSURLErrorNotConnectedToInternet:
        print("No internet")
    default:
        print("Some other error")
    }
}

更多信息在这里/a> and 在这里

To get the error returned, you need to use the alternative functions of downloadTask that have acompletionHandler`

self.urlSsn?.downloadTask(with: MyURLRequest, completionHandler: { data, response, error -> Void in
    if let error = error {
        print("\(error.localizedDescription)")
        // This should print "A data connection is not currently allowed."
    }
}

A similar is available for downloadTask(withResumeData) as well.

If you want to compare specific error codes (as error code -1020 in your example). You can do the following:

if let error = error {
    let e = error! as NSError
    switch e.code {
    case NSURLErrorNotConnectedToInternet:
        print("No internet")
    default:
        print("Some other error")
    }
}

More info here and here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文