您应该使用 KVO 观察对象的fractionCompleted
属性:NSProgress
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
和/或object
参数来决定这是否是您要观察的对象/属性。
您还可以使用setDownloadTaskDidWriteDataBlock:
from AFURLSessionManager
(from which AFHTTPSessionManager
inherits) 的方法来设置接收下载进度更新的块。
[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
协议映射到更方便的块机制。
顺便说一句,Apple 的 KVO 实现被严重破坏。我建议使用更好的实现,例如 Mike Ash 提出的带有MAKVONotificationCenter的实现。如果您有兴趣了解为什么 Apple 的 KVO 被破坏,请阅读Mike Ash 的Key-Value Observing Done Right。