Swift:如何在后台URLSession.downloadTask上捕获磁盘已满错误?

时间:2019-03-22 16:56:41

标签: ios swift nsurlsessiondownloadtask urlsession

我正在努力理解自己认为简单的事情。

我有一个URLSession.downloadTask。我已将下载对象设置为URLSession委托,并且以下委托方法确实会接收调用,因此我知道我的委托设置正确。

func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

我无法捕获的情况是downloadTask填满了iPad上的磁盘空间。这些委托方法都不会被调用。

我应该如何捕获此错误?

这是我的下载对象:

import Foundation
import Zip
import SwiftyUserDefaults

extension DownloadArchiveTask: URLSessionDownloadDelegate {

    // Updates progress info
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
                    didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
                    totalBytesExpectedToWrite: Int64) {


        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        self.delegate?.updateProgress(param: progress)
    }

    // Stores downloaded file
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

        print("DownloadArchiveTask: In didFinishDownloadingTo")

    }
}

extension DownloadArchiveTask: URLSessionTaskDelegate {

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        print("DownloadArchiveTask: In didCompleteWithError")
        if error != nil {
            print("DownloadArchiveTask: has error")
            self.delegate?.hasDiskSpaceIssue()
        }
    }
}

extension DownloadArchiveTask: URLSessionDelegate {
    // Background task handling
    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        print("DownloadArchiveTask: In handler for downloading archive")
        DispatchQueue.main.async {
            let sessionIdentifier = session.configuration.identifier
            if let sessionId = sessionIdentifier, let app = UIApplication.shared.delegate as? AppDelegate, let handler = app.completionHandlers.removeValue(forKey: sessionId) {
                handler()
            }
        }
    }
    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
        print("DownloadArchiveTask: didBecomeInvalidWithError")
        if error != nil {
            print("DownloadArchiveTask: has error")
            self.delegate?.hasDiskSpaceIssue()
        }
    }
}

class DownloadArchiveTask: NSObject {
    var delegate: UIProgressDelegate?
    var archiveUrl:String = "http://someurl.com/archive.zip"

    var task: URLSessionDownloadTask?

    static var shared = DownloadArchiveTask()

    // Create downloadsSession here, to set self as delegate
    lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background_archive")
        return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    }()

    func initialDownload() {
        // Create URL to the source file you want to download
        let fileURL = URL(string: archiveUrl)

        let request = URLRequest(url:fileURL!)

        self.task = self.session.downloadTask(with: request)
        task?.resume()

    }
}

有人做过吗?我不敢相信这很难-我必须以错误的方式解决问题...

1 个答案:

答案 0 :(得分:0)

不久前,我不得不为公司解决此问题。现在我的解决方案是在Objective C中进行的,因此您必须将其转换为Swift,这并不难。我创建了一个方法,该方法将可用存储空间留在设备上,然后根据我们正在下载的文件的大小检查该方法。我的解决方案假定您知道下载文件的大小,在这种情况下,可以在totalBytesExpectedToWrite方法中使用didWriteData参数。

这就是我所做的:

+ (unsigned long long)availableStorage
{
     unsigned long long totalFreeSpace = 0;
     NSError* error = nil;

     NSArray* paths = NSSearchPathForDirectoriesInDomain(NSDocumentDirectory, NSUserDomainMask, YES);
     NSDictionary* dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error:&error];
     if (dictionary)
     {
          NSNumber* freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
          totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
     }
     return totalFreeSpace;
}

请确保您为这些数字留一些误差的空间,因为iTunes,设备上的设置应用程序和该数字永远不会匹配。我们在这里得到的数字是三个中的最小数字,以MB为单位。希望对您有所帮助,并让我知道您是否需要将其转换为Swift的帮助。