I want to display file download progress (how many bytes are received) of particular file. It works fine with the NSURLSessionDownloadTask .My question is I want to achieve
Since iOS 11.0 and macOS 10.13, URLSessionTask
(former NSURLSessionTask
) adopted the ProgressReporting protocol. That means you can use the progress property to track the progress of a session task.
Expecting you already know how to use KVO observers, you can do something like:
task = session.downloadTask(with: url)
task.resume()
task.progress.addObserver(self, forKeyPath: "fractionCompleted", options: .new, context: &self.progressKVOContext)
and observe the value with:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &self.progressKVOContext, let keyPath = keyPath {
switch keyPath {
case "fractionCompleted":
guard let progress = object as? Progress else {
return
}
DispatchQueue.main.async { [weak self] in
self?.onDownloadProgress?(progress.fractionCompleted)
}
case "isCancelled":
cancel()
default:
break
}
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
OperationQueue
has now a progress property.
For example, the UIProgressView
can observe that property and update the progress value automatically using the observedProgress. Full example in https://nshipster.com/ios-13/#track-the-progress-of-enqueued-operations.