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
(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
プロトコルからより便利なブロック メカニズムにマップします。
ところで、Apple の KVO 実装はひどく壊れています。Mike Ash がMAKVONotificationCenterで提案したような、より優れた実装を使用することをお勧めします。Apple の KVO が壊れている理由に興味がある場合は、Mike Ash によるKey-Value Observing Done Rightをお読みください。