ios – 如何使用AFNetworking 3.0中的AFHTTPSessionManager获取下载进度

当我使用AFNetworking 2时,我可以像AFMTPRequestOperation一样取得进展:

NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:aURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:_timeoutInterval];
AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
imageRequestOperation.responseSerializer = [AFImageResponseSerializer serializer];

__weak AFHTTPRequestOperation *imageRequestOperationForBlock = imageRequestOperation;

[imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responSEObject) {
    // ...
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
    // ...
}];

[imageRequestOperation setDownloadProgressBlock:^(NSUInteger bytesRead,long long totalBytesRead,long long totalBytesExpectedToRead) {
    if (progress) {
        progress((float)totalBytesRead / totalBytesExpectedToRead);
    }
}];

我使用AFHTTPSessionManager GET:参数:成功:失败:获取数据,但我不知道如何在AFNetworking 3.0中获得下载进度.

解决方法

评论中的链接是missleading(NSURLSessionDownloadTask).对于那个很抱歉.

下面的代码应该可行.

假设:此代码放在AFHTTPSessionManager子类中,并声明了NSURLSessionDataTask * testTask ivar.它应该很容易根据需要进行修改.

代码的重要部分取自this answer

- (void)test
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://eoimages.gsfc.nasa.gov/images/imagerecords/78000/78797/nwpassage_tmo_2012199_lrg.jpg"]];

    testTask = [self dataTaskWithRequest:request
                       completionHandler:^(NSURLResponse * __unused response,id responSEObject,NSError *error) {

                           if (error)
                           {
                               //...
                               NSLog(@"error");
                           }
                           else
                           {
                               //...

                               UIImage *result = responSEObject;

                               NSLog(@"Success: %@",NsstringFromCGSize(result.size));
                           }
                       }];

    [self setDataTaskDidReceiveDataBlock:^(NSURLSession *session,NSURLSessionDataTask *dataTask,NSData *data)
     {
         if (dataTask.countOfBytesExpectedToReceive == NSURLSessionTransferSizeUnkNown)
           return;

         if (dataTask != testTask)
           return;

         NSUInteger code = [(NSHTTPURLResponse *)dataTask.response statusCode];

         if (!(code> 199 && code < 400))
           return;

         long long  bytesReceived = [dataTask countOfBytesReceived];
         long long  bytesTotal = [dataTask countOfBytesExpectedToReceive];

         NSLog(@"... %lld/%lld",bytesReceived,bytesTotal);
     }];

    [testTask resume];
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...