如何使用assetForURL加载带有URL列表的多张照片

时间:2013-03-10 21:50:18

标签: objective-c callback alassetslibrary

对于URL列表,我需要使用ALAssetsLibrary:assetForURL加载照片,并在一个方法中加载。 正如我们所知道的那样,由于此方法可以异步运行,但它不会遍历传递的URL列表。 我找到了这个片段(应该可以使用):

- (void)loadImages:(NSArray *)imageUrls loadedImages:(NSArray *)loadedImages callback:  (void(^)(NSArray *))callback
{
if (imageUrls == nil || [imageUrls count] == 0) {
    callback(loadedImages);
}
else {
    NSURL *head = [imageUrls head];
    __unsafe_unretained id unretained_self = self;        
    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:head resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *assetRepresentation = asset.defaultRepresentation;

        UIImage *image = [UIImage imageWithCGImage:assetRepresentation.fullResolutionImage scale:assetRepresentation.scale orientation:(UIImageOrientation)assetRepresentation.orientation];

        [unretained_self loadImages:[imageUrls tail] loadedImages:[loadedImages arrayByAddingObject:image] callback:callback];
    } failureBlock:^(NSError *error) {
        [unretained_self loadImages:[imageUrls tail] loadedImages:loadedImages callback:callback];
    }];
}
}

如何在表单中编写方法定义(在所有回调之上)

void loadImages(NSArray *imageUrls, NSArray *loadedImages, ...)  ?

如何从另一种方法(再次主要是回调部分)调用此方法? 回调可以是调用方法还是第三种方法?这个方法需要如何编写? 我在这里找到了代码段:http://www.calebmadrigal.com/functional-programming-deal-asynchronicity-objective-c/

1 个答案:

答案 0 :(得分:1)

使用NSThread调用 loadImages 方法。

NSMutableArray *imageCollection = [NSThread detachNewThreadSelector:@selector (loadImages:)
                         toTarget:self 
                       withObject:imageUrlsCollection];


- (NSMutableArray *)loadImages:(NSArray *)imageUrls 
{
  ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
  NSMutableArray *loadedImages = [[NSMutableArray alloc] init];

  @try
  {
    for(int index = 0; index < [imageUrls count]; index++)
    {
      NSURL *url = [imageUrls objectAtIndex:index];

      [library assetForURL:url resultBlock:^(ALAsset *asset) {

         ALAssetRepresentation *assetRepresentation = asset.defaultRepresentation;

         dispatch_async(dispatch_get_main_queue(), ^{

             UIImage *image = [UIImage imageWithCGImage:assetRepresentation.fullResolutionImage scale:assetRepresentation.scale orientation:(UIImageOrientation)assetRepresentation.orientation];

             [loadedImages addObject:image];

          });

     } failureBlock:^(NSError *error) {

          NSLog(@"Failed to get Image");
     }];

    }
 }
 @catch (NSException *exception)
 {
     NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
 }
 @finally
 {
   return loadedImages;
 }

}

注意:使用 ARC ,请注意无效尝试访问ALAssetPrivate超过其拥有的ALAssetsLibrary 问题的生命周期

Here is the fix:)