ReactNative图片下载过程(二)

本文承接ReactNative图片下载过程(一),继续深入研究。源码在文末,如想直接看可翻至最后。

整个图片的下载过程,基本思想就是先在模块里找合适的loader去下载,如果找不到则用RCTNetwork去下,当然我们看源码肯定不能只懂思想,一些细节处理也是很值得关注的,比如缓存处理,缓存的访问限制,取消下载的处理,下载完回调函数的线程处理等等。

1、处理图片下载完成后的回调函数,将回调函数放在非主线程中处理,防止耗费资源,不得不说其对于输入的判断都很到位

  RCTImageLoaderCompletionBlockcompletionHandler = ^(NSError*error, UIImage*image) {
    if([NSThreadisMainThread]) {
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (!cancelled) {
         completionBlock(error, image);
       }
     });
    } elseif(!cancelled) {
     completionBlock(error, image);
   }
 };

2、判断图片的URL是否为空,如果为空则抛出错误。

 if(imageTag.length== 0) {
   completionHandler(RCTErrorWithMessage(@"source.uri should not be an empty string"), nil);
   return^{};
 }

3、建NSURLCache串行队列

  // All accessto URL cache must be serialized
  if(!_URLCacheQueue) {
    _URLCacheQueue= dispatch_queue_create("com.facebook.react.ImageLoaderURLCacheQueue", DISPATCH_QUEUE_SERIAL);
  }

4、异步执行队列_URLCacheQueue,初始化URLCache缓存

    if(!_URLCache) {
      _URLCache= [[NSURLCachealloc] initWithMemoryCapacity:5* 1024* 1024// 5MB
                                              diskCapacity:200* 1024* 1024// 200MB
                                                  diskPath:@"React/RCTImageDownloader"];
   }

5、找到可以执行下载操作的loader,如果找到则执行下载操作loadImageForURL:

    RCTImageLoader*strongSelf = weakSelf;
    if(cancelled || !strongSelf) {
      return;
   }
 
    // Findsuitable image URL loader
    NSURLRequest*request = [RCTConvertNSURLRequest:imageTag];
    id<RCTImageURLLoader> loadHandler = [strongSelf imageURLLoaderForURL:request.URL];
    if(loadHandler) {
      cancelLoad = [loadHandler loadImageForURL:request.URL
                                         size:size
                                        scale:scale
                                    resizeMode:resizeMode
                               progressHandler:progressHandler
                             completionHandler:completionHandler]?: ^{};
      return;
   }

6、调试用,检查网络模块是否可用并能下载图片

    // Checkif networking module is available
    if(RCT_DEBUG&& ![_bridgerespondsToSelector:@selector(networking)]) {
      RCTLogError(@"No suitableimage URL loader found for %@. You may need to "
                 " import the RCTNetworkinglibrary in order to load images.",
                 imageTag);
      return;
   }
 
    // Checkif networking module can load image
    if(RCT_DEBUG&& ![_bridge.networkingcanHandleRequest:request]) {
      RCTLogError(@"No suitableimage URL loader found for %@",imageTag);
      return;
   }

7、使用网络模块来下载图片

    __blockRCTImageLoaderCancellationBlockcancelDecode = nil;
    RCTURLRequestCompletionBlockprocessResponse =
    ^(NSURLResponse*response, NSData*data, NSError*error) {
 
      // 检查是否有下载出错或没有数据返回
      if(error) {
        completionHandler(error, nil);
        return;
      } elseif(!data) {
        completionHandler(RCTErrorWithMessage(@"Unknown image download error"), nil);
        return;
     }
 
      // 检查HTTP请求是否返回错误,如有误则抛出返回的状态码
      if([response isKindOfClass:[NSHTTPURLResponseclass]]) {
        NSInteger statusCode =((NSHTTPURLResponse*)response).statusCode;
        if (statusCode != 200) {
          completionHandler([[NSError alloc] initWithDomain:NSURLErrorDomain
                                                     code:statusCode
                                                 userInfo:nil], nil);
          return;
       }
     }
 
      // 图片解码
      cancelDecode = [strongSelf decodeImageData:data
                                          size:size
                                         scale:scale
                                     resizeMode:resizeMode
                                completionBlock:completionHandler];
   };

8、添加png后缀

    //判断请求的url是否为fileURL并且是否没有后缀,如果都是则添加后缀png
    if(request.URL.fileURL&& request.URL.pathExtension.length== 0) {
      NSMutableURLRequest*mutableRequest = [request mutableCopy];
      mutableRequest.URL = [NSURL fileURLWithPath:[request.URL.path stringByAppendingPathExtension:@"png"]];
     request = mutableRequest;
   }
 

9、根据request在responseCache缓存中查找是否已经有了缓存,如果有则执行缓存内容

    NSCachedURLResponse*cachedResponse = [_URLCachecachedResponseForRequest:request];
    if(cachedResponse) {
      processResponse(cachedResponse.response,cachedResponse.data, nil);
      return;
   }
 

10、使用RCTNetworkTask来下载图片

    //调用network模块来发起请求
    RCTNetworkTask*task = [_bridge.networkingnetworkTaskWithRequest:request completionBlock:
                           ^(NSURLResponse*response, NSData*data, NSError*error) {
      if(error) {
        completionHandler(error, nil);
        return;
     }
 
      dispatch_async(_URLCacheQueue, ^{
 
        // 将请求的回应缓存起来
        BOOL isHTTPRequest =[request.URL.scheme hasPrefix:@"http"];
        [strongSelf->_URLCache storeCachedResponse:
         [[NSCachedURLResponse alloc] initWithResponse:response
                                                data:data
                                            userInfo:nil
                                       storagePolicy:isHTTPRequest ? NSURLCacheStorageAllowed: NSURLCacheStorageAllowedInMemoryOnly]
                                      forRequest:request];
 
        // 处理返回的数据
        processResponse(response,data, nil);
 
     });
 
   }];

11、开始下载

    task.downloadProgressBlock= progressHandler;
    [task start];
 
   cancelLoad = ^{
      [task cancel];
      if(cancelDecode) {
       cancelDecode();
     }
   };

12、返回一个可取消下载的block

  return^{
    if(cancelLoad) {
     cancelLoad();
   }
//执行1和cancelled的或运算然后把结果存入&cancelled
    OSAtomicOr32Barrier(1, &cancelled);
 };

官方部分源码

RCTImageLoader.m

- (RCTImageLoaderCancellationBlock)loadImageWithTag:(NSString*)imageTag
                                             size:(CGSize)size
                                            scale:(CGFloat)scale
                                       resizeMode:(UIViewContentMode)resizeMode
                                    progressBlock:(RCTImageLoaderProgressBlock)progressHandler
                                  completionBlock:(RCTImageLoaderCompletionBlock)completionBlock
{
  __blockvolatileuint32_tcancelled = 0;
  __blockvoid(^cancelLoad)(void) = nil;
  __weakRCTImageLoader*weakSelf = self;
 
  RCTImageLoaderCompletionBlockcompletionHandler = ^(NSError*error, UIImage*image) {
    if([NSThreadisMainThread]) {
 
      //Most loaders do not return on the main thread, so caller is probably not
      //expecting it, and may do expensive post-processing in the callback
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (!cancelled) {
         completionBlock(error, image);
       }
     });
    } elseif(!cancelled) {
     completionBlock(error, image);
   }
 };
 
  if(imageTag.length== 0) {
    completionHandler(RCTErrorWithMessage(@"source.uri should not be an empty string"), nil);
    return^{};
  }
 
  // All accessto URL cache must be serialized
  if(!_URLCacheQueue) {
    _URLCacheQueue= dispatch_queue_create("com.facebook.react.ImageLoaderURLCacheQueue", DISPATCH_QUEUE_SERIAL);
  }
  dispatch_async(_URLCacheQueue, ^{
 
    if(!_URLCache) {
      _URLCache= [[NSURLCachealloc] initWithMemoryCapacity:5* 1024* 1024// 5MB
                                              diskCapacity:200* 1024* 1024// 200MB
                                                  diskPath:@"React/RCTImageDownloader"];
   }
 
    RCTImageLoader*strongSelf = weakSelf;
    if(cancelled || !strongSelf) {
      return;
   }
 
    // Findsuitable image URL loader
    NSURLRequest*request = [RCTConvertNSURLRequest:imageTag];
    id<RCTImageURLLoader> loadHandler = [strongSelf imageURLLoaderForURL:request.URL];
    if(loadHandler) {
      cancelLoad = [loadHandler loadImageForURL:request.URL
                                         size:size
                                        scale:scale
                                    resizeMode:resizeMode
                               progressHandler:progressHandler
                             completionHandler:completionHandler]?: ^{};
      return;
   }
 
    // Checkif networking module is available
    if(RCT_DEBUG&& ![_bridgerespondsToSelector:@selector(networking)]) {
      RCTLogError(@"No suitableimage URL loader found for %@. You may need to "
                 " import the RCTNetworkinglibrary in order to load images.",
                 imageTag);
      return;
   }
 
    // Checkif networking module can load image
    if(RCT_DEBUG&& ![_bridge.networkingcanHandleRequest:request]) {
      RCTLogError(@"No suitableimage URL loader found for %@",imageTag);
      return;
   }
 
    // Usenetworking module to load image
    __blockRCTImageLoaderCancellationBlockcancelDecode = nil;
    RCTURLRequestCompletionBlockprocessResponse =
    ^(NSURLResponse*response, NSData*data, NSError*error) {
 
      //Check for system errors
      if(error) {
        completionHandler(error, nil);
        return;
      } elseif(!data) {
        completionHandler(RCTErrorWithMessage(@"Unknown image download error"), nil);
        return;
     }
 
      //Check for http errors
      if([response isKindOfClass:[NSHTTPURLResponseclass]]) {
        NSInteger statusCode =((NSHTTPURLResponse*)response).statusCode;
        if (statusCode != 200) {
          completionHandler([[NSError alloc] initWithDomain:NSURLErrorDomain
                                                     code:statusCode
                                                 userInfo:nil], nil);
          return;
       }
     }
 
      //Decode image
      cancelDecode = [strongSelf decodeImageData:data
                                          size:size
                                         scale:scale
                                     resizeMode:resizeMode
                                completionBlock:completionHandler];
   };
 
    // Addmissing png extension
    if(request.URL.fileURL&& request.URL.pathExtension.length== 0) {
      NSMutableURLRequest*mutableRequest = [request mutableCopy];
      mutableRequest.URL = [NSURL fileURLWithPath:[request.URL.path stringByAppendingPathExtension:@"png"]];
     request = mutableRequest;
   }
 
    // Checkfor cached response before reloading
    // TODO:move URL cache out of RCTImageLoader into its own module
    NSCachedURLResponse*cachedResponse = [_URLCachecachedResponseForRequest:request];
    if(cachedResponse) {
      processResponse(cachedResponse.response,cachedResponse.data, nil);
      return;
   }
 
    //Download image
    RCTNetworkTask*task = [_bridge.networkingnetworkTaskWithRequest:request completionBlock:
                           ^(NSURLResponse*response, NSData*data, NSError*error) {
      if(error) {
        completionHandler(error, nil);
        return;
     }
 
      dispatch_async(_URLCacheQueue, ^{
 
        // Cache the response
        // TODO: move URL cache out of RCTImageLoader into itsown module
        BOOL isHTTPRequest =[request.URL.scheme hasPrefix:@"http"];
        [strongSelf->_URLCache storeCachedResponse:
         [[NSCachedURLResponse alloc] initWithResponse:response
                                                data:data
                                            userInfo:nil
                                       storagePolicy:isHTTPRequest ? NSURLCacheStorageAllowed: NSURLCacheStorageAllowedInMemoryOnly]
                                      forRequest:request];
 
        // Process image data
        processResponse(response,data, nil);
 
     });
 
   }];
    task.downloadProgressBlock= progressHandler;
    [task start];
 
   cancelLoad = ^{
      [task cancel];
      if(cancelDecode) {
       cancelDecode();
     }
   };
 
 });
 
  return^{
    if(cancelLoad) {
     cancelLoad();
   }
    OSAtomicOr32Barrier(1, &cancelled);
 };
}

如果你也对ReactNative感兴趣,欢迎一起研究。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,568评论 25 707
  • Xutils3.0技术分享1.这个技术分享的目的1.首先要让大家了解Xutil3.0是什么Xtuils3.0的前身...
    wodezhuanshu阅读 3,006评论 5 9
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,612评论 4 59
  • 在这个漂浮的城市里,我们卑微着,依然渴望飞翔。 也许我们只是需要一个拥抱,用来知道,我们并不孤单。 不是我们慢,是...
    Andersony阅读 233评论 0 1
  • 电梯不过是架垂直升降机,完全可以看作是交通工具的一种,乘客在站点等,到不同的地点下,有公共汽车的特点,只不过我们多...
    凭栏听风阅读 223评论 0 0