您应该观察fractionCompleted
你的财产NSProgress
使用 KVO 的对象:
NSURL *url = [NSURL URLWithString:@"http://www.hfrmovies.com/TheHobbitDesolationOfSmaug48fps.mp4"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
NSProgress *progress;
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
// …
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
[progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL];
// …
}];
[downloadTask resume];
[progress addObserver:self
forKeyPath:@"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:NULL];
然后添加观察者方法:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"fractionCompleted"]) {
NSProgress *progress = (NSProgress *)object;
NSLog(@"Progress… %f", progress.fractionCompleted);
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
当然,你应该检查一下keyPath
and/or object
参数来决定这是否是您想要观察的对象/属性。
您还可以使用setDownloadTaskDidWriteDataBlock:
方法来自AFURLSessionManager
(从中AFHTTPSessionManager
继承)设置接收下载进度更新的块。
[session setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
NSLog(@"Progress… %lld", totalBytesWritten);
}];
此 AFNetworking 方法映射URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
方法来自NSURLSessionDownloadDelegate
协议到更方便的块机制。
顺便说一句,苹果的 KVO 实现被严重破坏。我建议使用更好的实现,例如 Mike Ash 提出的MAKVO通知中心 https://github.com/mikeash/MAKVONotificationCenter。如果您有兴趣了解 Apple 的 KVO 被破坏的原因,请阅读正确地进行键值观察 https://mikeash.com/pyblog/key-value-observing-done-right.html作者:迈克·阿什。