-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?

1
  • Use completion block. You just can't synchronously return the result from asynchronous call (without blocking UI and without time travel). Commented May 5, 2016 at 10:39

1 Answer 1

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; }); }); } 
Sign up to request clarification or add additional context in comments.

2 Comments

it will get a error , build failed . How to fix it?
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.