progress.fractionCompleted

来源:互联网 发布:freebsd mysql 编辑:程序博客网 时间:2024/06/05 11:03

  

    // MARK: 载文件

    /**

     载文件

     

     - parameter urlStr:      文件的网络地址

     - parameter savePath:    保存路径(包含文件名)

     - parameter progress:    进度

     - parameter resultBlock: 结果回调

     */

    func download(urlStr:String, savePath: String, progress: ((_ progress:Double) -> ())?, resultBlock: ((URL?,Error?)->())?) {

        let urlRequest =URLRequest(url: URL(string: urlStr)!)

        let task =self.downloadTask(with: urlRequest, progress: {

            if progress !=nil {

                progress!(($0.fractionCompleted))

            }

        }, destination: { (url, response) -> URLin

            returnURL(fileURLWithPath: savePath)

        }, completionHandler: { (response, url, error) in

            if resultBlock !=nil {

                resultBlock!(url, error)

            }

        })

        

        task.resume()

    }


////////////////////////////////////////////////////////////////


追踪下载进度


在下载开始之后,请求会开始更新progress,这是一个NSProgress类型的属性。app通过对progress.fractionCompleted进行KVO来追踪下载进度。这需要开始和结束观察,以及添加当值改变时执行的代码。列表4-6展示了如何开始和结束观察进度。列表4-7展示了当值改变时执行的代码。

列表4-6 开始和结束追踪下载进度

1
2
3
4
5
// Start observing fractionCompleted for the progress
[self.resourceRequest.progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
  
// Stop observing fractionCompleted for the progress
[self.resourceRequest.progress removeObserver:self forKeyPath:@"fractionCompleted"];

列表4-7 当fractionCompleted的值改变时执行的代码

1
2
3
4
5
6
7
8
9
//
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // Check for the progress object and key
    if ((object == self.resourceRequest.progress) && ([keyPath isEqualToString:@"fractionCompleted])) {
        double progressSoFar = self.resourceRequest.progress.fractionCompleted;
        // do something with the value
    }
}
  

追踪下载的两个重要用途是:

  • 调整下载优先级。如果下载时间过长可以提高优先级,如果时间充裕可以降低优先级。

  • 为用户提供下载进度反馈。可以使用一个简单的进度条来反馈fractionCompleted的值。



0 0