AFNetworking 3.0 setImageWithURLRequest下载进度

有没有人有一个很好的工作解决scheme,以获得使用UIImageView + AFNetworking类别和AFNetworking 3.0下载进度。

这个类别 ,我曾经使用的3.0版本已经停止工作了。

这是我自己的实验版本 ,可悲的是,现在,随机崩溃。

这里是AFNetworking 3.0的修改版本,您可以在使用UIImageView + AFNetworking类别从服务器加载图像时显示进度。

https://github.com/rushisangani/AFNetworking

请用原始AFNetworking文件replace下列文件。

UIImageView+AFNetworking.h, UIImageView+AFNetworking.m, UIImage+ImageDownloader.h, UIImage+ImageDownloader.m 

注:如果您更新您的吊舱,那么这将被删除。

如果你看AFImageDownloader这个,它被UIImageView类用来下载图像。 你在这个class上

 - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest: (NSURLRequest *)request success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 

它返回一个有NSURLSessionDataTask *任务属性的收据。 NSURLSessionDataTask具有不同的字节下载,期望的字节接收等属性。也许你可以使用这个,实现你的任务。

你可以通过在UIImageView + AFNetworking.h中添加几行来实现

  1. 将此代码放置在导入语句下的文件顶部

     static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; 
  2. 并且你需要注册观察者来追踪接收到的字节,在函数setImageWithURLRequest下面添加下面一行的位置

     if (cachedImage) { // AFNetworking default code } else{ // AFNetworking default code // Our new lines to track the download [self.af_activeImageDownloadReceipt.task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; [self.af_activeImageDownloadReceipt.task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; } 
  3. 最后添加这个新function。

     #pragma mark - NSKeyValueObserving - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(__unused NSDictionary *)change context:(void *)context { if (context == AFTaskCountOfBytesReceivedContext) { if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { if ([object countOfBytesExpectedToReceive] > 0) { dispatch_async(dispatch_get_main_queue(), ^{ //You can do your stuff at here like show progress NSLog(@"Progress : %f",[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f)); }); } } if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { @try { [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; NSLog(@"Image Download Complete"); if (context == AFTaskCountOfBytesReceivedContext) { [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; } } @catch (NSException * __unused exception) {} } } } }