异步NSImage下载:第一个图像具有无限加载

时间:2015-09-12 20:03:10

标签: ios objective-c uiimage react-native

我正在尝试使用NYTPhotoViewer和异步图像下载为react-native创建一个模块。它可以工作,但是当其他下载和显示时,第一个图像永远不会停止为动画加载。有趣的是,如果我滑动一些图像(2和更多),第一个图像将呈现。代码在这里:

#import <NYTPhotoViewer/NYTPhotosViewController.h>
#import "NYTImageViewer.h"
#import "NYTExamplePhoto.h"

@interface NYTImageViewer () <NYTPhotosViewControllerDelegate>
  @property (nonatomic) NSArray *photos;
@end

@implementation NYTImageViewer

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(open:(NSArray *)urls)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    NSArray *photos = addPhotos(urls);

    NYTPhotosViewController *photosViewController = [[NYTPhotosViewController alloc] initWithPhotos:photos];

    UIViewController *ctrl = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

    [ctrl presentViewController:photosViewController animated:TRUE completion: nil];
  });
}

NSArray* addPhotos(NSArray *urls) {
  NSMutableArray *photos = [NSMutableArray array];
  for (int i = 0; i < [urls count]; i++) {
    NYTExamplePhoto *photo = [[NYTExamplePhoto alloc] init];
    dispatch_async(dispatch_get_global_queue(0,0), ^{
      NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urls[i]]];
      if ( imageData == nil )
        return;
      dispatch_async(dispatch_get_main_queue(), ^{
        photo.image = [UIImage imageWithData: imageData];
      });
    });
    [photos addObject:photo];
  }

  return photos;
}
@end

我该如何解决?

1 个答案:

答案 0 :(得分:0)

你不应该/不能从远程URL加载,并且dispatch_async它会产生预期的行为:

NSData * _data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urls[i]]];

您必须通过异步方法使用NSURLSessionNSURLConnection进行远程调用,并且您必须在回调时处理递归。