当应用程序在iOS12中进入后台时,URLSessionDelegate的didWriteData不调用

时间:2018-11-23 09:14:19

标签: swift downloading ios12

我想实现下载功能,该功能可以用百分比显示下载任务的完成状态。我可以做到,但是问题是当应用程序移至后台并在那时又回到前台时,didWriteData中未调用委托方法iOS12。谁能帮帮我吗?这是我的代码

protocol DownloadDelagate {
    func downloadingProgress(value:Float)
    func downloadCompleted(identifier: Int,url: URL)
}

class DownloadManager : NSObject, URLSessionDelegate, URLSessionDownloadDelegate {

    static var shared = DownloadManager()
    var delegate: DownloadDelagate?
    var backgroundSessionCompletionHandler: (() -> Void)?

    var session : URLSession {
        get {

            let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
            config.isDiscretionary = true
            config.sessionSendsLaunchEvents = true
            return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
        }
    }

    private override init() {
    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        DispatchQueue.main.async {
            if let completionHandler = self.backgroundSessionCompletionHandler {
                self.backgroundSessionCompletionHandler = nil
                completionHandler()
            }
        }
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        delegate?.downloadCompleted(identifier: downloadTask.taskIdentifier, url: location)
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        if totalBytesExpectedToWrite > 0 {
            let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
            let progressPercentage = progress * 100
            delegate?.downloadingProgress(value: progressPercentage)
            print("Download with task identifier: \(downloadTask.taskIdentifier) is \(progressPercentage)% complete...")
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            print("Task failed with error: \(error)")
        } else {
            print("Task completed successfully.")
        }
    }
}

2 个答案:

答案 0 :(得分:2)

基于this thread,这是NSURLSesstion中的错误。当前,存在已知的解决方法(Apple工程师批准):

var session: URLSession?
...
func applicationDidBecomeActive(_ application: UIApplication) {
    session?.getAllTasks { tasks in
        tasks.first?.resume() // It is enough to call resume() on only one task
        // If it didn't work, you can try to resume all
        // tasks.forEach { $0.resume() }
    }
}

答案 1 :(得分:0)

请在AppDelegate的applicationWillEnterForeground()中尝试您的代码。当应用程序从“背景”状态变为“活动”状态时,您可以在此处进行更改。