Showing the file download progress with NSURLSessionDataTask

前端 未结 4 628
感情败类
感情败类 2020-12-01 06:49

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

4条回答
  •  既然无缘
    2020-12-01 06:57

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

    iOS 13 update

    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.

提交回复
热议问题