ReactNative中图片下载过程(一)

1771 查看

本文旨在讲解ReactNative中的图片下载过程:
  • 取消当前的下载,
  • 下载前先执行onLoadStart回调,
  • 生成下载过程的回调,
  • 下载图片,
  • 下载结束后的回调。

可以看到下载过程并不复杂,思想都是相通的,只不过Facebook面向的是全世界的开发者,遇到的问题或要满足的需求也是世界范围内的,
所以其对细节方面的处理相当到位,特别是对线程的关注,错误处理,总之每一处都值得回味,这也是我想读源码的原因之一。
文末附有本文说到的全部源码,如想直接看源码可翻至最后。

1、取消当前正在下载的图片

- (void)cancelImageLoad
{
  RCTImageLoaderCancellationBlock previousCancellationBlock = _reloadImageCancellationBlock;
  if(previousCancellationBlock) {
   previousCancellationBlock();
    _reloadImageCancellationBlock = nil;
  }
}

2、执行图片下载前的回调

    if(_onLoadStart) {
      _onLoadStart(nil);
   }

3、生成图片调用过程中的回调,原生会传两个参数给JS端,loaded和total

用于显示下载进度,其中loaded是当前的下载量,而total是下载总量,如果下载一张2M的图片,那么total就是2M,而loaded会随着下载而变化。

    RCTImageLoaderProgressBlockprogressHandler = nil;
    if(_onProgress) {
      progressHandler = ^(int64_t loaded, int64_t total) {
        _onProgress(@{
          @"loaded": @((double)loaded),
          @"total": @((double)total),
        });
     };
   }

4、执行图片加载,后文会详细分析。

    _reloadImageCancellationBlock= [_bridge.imageLoaderloadImageWithTag:_source.imageURL.absoluteString
                                                                  size:self.bounds.size
                                                                 scale:RCTScreenScale()
                                                            resizeMode:self.contentMode
                                                          progressBlock:progressHandler
                                                        completionBlock:^(NSError *error, UIImage *image) {

Tag:传入了一个NSString的imageURL,
size:当前RCTImageView的大小
scale:屏幕的缩放比例(这种需求都考虑到……),作用就是如果当前屏幕被放大,那么下载下来的图片也会根据屏幕缩放比例来放大。
progressBlock:下载过程的回调函数
completionBlock:下载完成后的回调

注意_reloadImageCancellationBlock返回的是可取消下载的block,这也是一个功能的痛点,取消下载图片。

5、下载完成后的回调

      dispatch_async(dispatch_get_main_queue(), ^{
        RCTImageView*strongSelf = weakSelf;
        if (![source isEqual:strongSelf.source]) {
          // Bail out if source has changed since we startedloading
          return;
       }
        if (image.reactKeyframeAnimation){
          [strongSelf.layer addAnimation:image.reactKeyframeAnimationforKey:@"contents"];
        } else {
          [strongSelf.layer removeAnimationForKey:@"contents"];
          strongSelf.image = image;
       }
        if (error) {
          if (strongSelf->_onError) {
            strongSelf->_onError(@{ @"error":error.localizedDescription});
         }
        } else {
          if (strongSelf->_onLoad) {
            strongSelf->_onLoad(nil);
         }
       }
        if (strongSelf->_onLoadEnd) {
           strongSelf->_onLoadEnd(nil);
       }
     });

下载完成后,先判断下载源有没有更改,如果被更改了,则返回不执行任何操作。

if (![source isEqual:strongSelf.source]) {}

然后是判断是否有没动画要求,有的话就执行动画,没有的话则不执行

        if (image.reactKeyframeAnimation){
          [strongSelf.layer addAnimation:image.reactKeyframeAnimationforKey:@"contents"];
        } else {
          [strongSelf.layer removeAnimationForKey:@"contents"];
          strongSelf.image = image;
       }

接着判断是否下载错误,错误的话执行onError回调,成功地话执行onLoad回调。

        if (error) {
          if (strongSelf->_onError) {
            strongSelf->_onError(@{ @"error":error.localizedDescription});
         }
        } else {
          if (strongSelf->_onLoad) {
            strongSelf->_onLoad(nil);
         }
       }

还有最后一个onLoadEnd不管下载过程成功与否都会执行的回调。

        if (strongSelf->_onLoadEnd) {
           strongSelf->_onLoadEnd(nil);
       }

其实这里的onLoad如果换成onLoadSuccess会好理解一点,官方文档的onLoad和onLoadEnd有疑惑性。


onLoad官方文档.png

官方部分源码

RCTImageView.m

- (void)reloadImage
{
  [selfcancelImageLoad];

  if(_source&& self.frame.size.width> 0&& self.frame.size.height> 0) {
    if(_onLoadStart) {
      _onLoadStart(nil);
   }

    RCTImageLoaderProgressBlockprogressHandler = nil;
    if(_onProgress) {
      progressHandler = ^(int64_t loaded, int64_t total) {
        _onProgress(@{
          @"loaded": @((double)loaded),
          @"total": @((double)total),
        });
     };
   }

    RCTImageSource*source = _source;
    __weakRCTImageView*weakSelf = self;
    _reloadImageCancellationBlock= [_bridge.imageLoaderloadImageWithTag:_source.imageURL.absoluteString
                                                                  size:self.bounds.size
                                                                 scale:RCTScreenScale()
                                                            resizeMode:self.contentMode
                                                          progressBlock:progressHandler
                                                        completionBlock:^(NSError *error, UIImage *image) {
      dispatch_async(dispatch_get_main_queue(), ^{
        RCTImageView*strongSelf = weakSelf;
        if (![source isEqual:strongSelf.source]) {
          // Bail out if source has changed since we startedloading
          return;
       }
        if (image.reactKeyframeAnimation){
          [strongSelf.layer addAnimation:image.reactKeyframeAnimationforKey:@"contents"];
        } else {
          [strongSelf.layer removeAnimationForKey:@"contents"];
          strongSelf.image = image;
       }
        if (error) {
          if (strongSelf->_onError) {
            strongSelf->_onError(@{ @"error":error.localizedDescription});
         }
        } else {
          if (strongSelf->_onLoad) {
            strongSelf->_onLoad(nil);
         }
       }
        if (strongSelf->_onLoadEnd) {
           strongSelf->_onLoadEnd(nil);
       }
     });
   }];
  } else{
    [selfclearImage];
  }
}