DidWriteData URLSessionDelegate не вызывает, когда приложение собирается в фоновом режиме в iOS12 - PullRequest
0 голосов
/ 23 ноября 2018

Я хочу реализовать функцию загрузки, которая может отображать завершенный статус задачи загрузки в процентах.И я могу это сделать, но проблема в том, что когда приложение переходит в фоновый режим и в это время возвращается на передний план, метод делегата 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 голосов
/ 20 июля 2019

На основании этой темы это ошибка в NSURLSesstion.В настоящее время существуют известные способы решения этой проблемы (одобрено 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() }
    }
}
0 голосов
/ 23 ноября 2018

Пожалуйста, попробуйте свой код в AppDelegate's applicationWillEnterForeground().Здесь вы можете внести изменения, когда приложение перейдет из фонового состояния в активное.

...