当应用程序在iOS12中进入后台时,URLSessionDelegate的didWriteData不调用 [英] URLSessionDelegate's didWriteData not call when app is going to background in iOS12

查看:69
本文介绍了当应用程序在iOS12中进入后台时,URLSessionDelegate的didWriteData不调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement downloading functionality which can show completed status of downloading task with the percentage. And I'm able to do that but the problem is when the app is moving to the background and come back to the foreground at that time the delegate method didWriteData is not called in iOS12. Can anyone please help me? Here is my code

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.")
        }
    }
}

推荐答案

基于此线程这是 NSURLSesstion 中的错误.当前,有一种已知的解决方法(由Apple工程师批准):

Based on this thread this is a bug in NSURLSesstion. Currently there are known workaround for this (approved by Apple Engineers):

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() }
    }
}

这篇关于当应用程序在iOS12中进入后台时,URLSessionDelegate的didWriteData不调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆