-1
-(UIImage *)getImageFromURL:(NSURL *)imageURL{
    __block UIImage *image = [UIImage new];
    PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
    PHAsset *asset = result.firstObject;
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestImageForAsset:asset targetSize:CGSizeMake(100, 100) contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        image = result;
    }];
    return image;
}

the code in block "image = result" execute after code out of block "return image" , so it always return nil. How can i make the code in block execute first. Use thread or NSOperation or GCD?

JJ.Yuan
  • 63
  • 12
  • Use completion block. You just can't synchronously return the result from asynchronous call (without blocking UI and without time travel). – Sulthan May 05 '16 at 10:39

1 Answers1

0
-(UIImage *)getImageFromURL:(NSURL *)imageURL{
     __block UIImage *image = [UIImage new];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
        PHAsset *asset = result.firstObject;
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestImageForAsset:asset targetSize:CGSizeMake(100, 100) contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            image = result;
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
             return image;
        });
    });
}
Bhadresh Mulsaniya
  • 2,610
  • 1
  • 12
  • 25
  • it will get a error , build failed . How to fix it? – JJ.Yuan May 05 '16 at 09:44
  • you cannot 'return image' in a block when this block has no return . Like function , block can also return value , but block 'dispatch_async' has no return – JJ.Yuan May 05 '16 at 09:50