如何在AFNetworking 2.0中获得下载进度?

gre*_*lom 25 objective-c ios afnetworking-2

我正在使用AFURLSessionManager创建一个新的下载任务:

AFURLSessionManager* manager = ...

NSProgress* p = nil;
NSURLSessionDownloadTask* downloadTask =
        [manager downloadTaskWithRequest:request
                                 progress:&p
                              destination:^NSURL*(NSURL* targetPath, NSURLResponse* response) {...}
                        completionHandler:^(NSURLResponse* response, NSURL* filePath, NSError* error) {...}
        ];
[downloadTask resume];
Run Code Online (Sandbox Code Playgroud)

该文件下载得很好,但是,如何获得进度通知?

p总是设为零.我已经为此提出了一个问题.

我也试着打电话setDownloadTaskDidWriteDataBlock给经理,我确实收到了进度通知,但是我在文件下载后将它们全部收到组合.

似乎这个区域在AFNetworking 2.0中仍然有点儿麻烦

有任何想法吗?

Sen*_*doa 45

您应该使用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];
Run Code Online (Sandbox Code Playgroud)

然后添加观察者方法:

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您应该检查keyPath和/或object参数以确定这是否是您要观察的对象/属性.

您还可以使用setDownloadTaskDidWriteDataBlock:方法AFURLSessionManager(从中AFHTTPSessionManager继承)来设置用于接收下载进度更新的块.

[session setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
    NSLog(@"Progress… %lld", totalBytesWritten);
}];
Run Code Online (Sandbox Code Playgroud)

该AFNetworking方法将URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:方法从NSURLSessionDownloadDelegate协议映射到更方便的块机制.

顺便说一下,Apple的KVO实施严重受损.我建议使用更好的实现,例如Mike Ash和MAKVONotificationCenter提出的实现.如果您有兴趣阅读为什么Apple的KVO被破坏,请阅读Mike Ash的Key-Value Observing Done Right.


CKD*_*CKD 18

我遇到了类似的问题,并找到了解决方案.

请查看以下链接:http: //cocoadocs.org/docsets/AFNetworking/2.0.1/Categories/UIProgressView+AFNetworking.html

#import <AFNetworking/UIKit+AFNetworking.h>
Run Code Online (Sandbox Code Playgroud)

并使用UIProgressView可用的其他方法

setProgressWithDownloadProgressOfTask:动画:

我是怎么做到的

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request  progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){
    NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) firstObject]];
    return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error){
    NSLog(@"File downloaded to: %@", filePath);

}];

[self.progressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
[downloadTask resume];
Run Code Online (Sandbox Code Playgroud)