Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read PHAsset content asynchronous

I want to read specified file (photo from camera roll) asynchronous, but it does not work for me.

Variable tempData gets nil untill I change config requestOptionForPhotos.synchronous to YES, then everything is ok, but I don't want to perform this code synchronous.

Is it possible that I'm blocking access to photo by requesting to the same file in other thread? I'm newbie in objective-c and iOS programming and I don't know how does it works.

  NSURL *assetUrl = [[NSURL alloc] initWithString:filepath];
  PHFetchResult *collection = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:assetUrl] options:nil];

  PHImageRequestOptions *requestOptionForPhotos = [[PHImageRequestOptions alloc] init];
  requestOptionForPhotos.networkAccessAllowed = YES;
  requestOptionForPhotos.synchronous = NO;

  __block BOOL isFinished = NO;
  __block NSData * tempData = nil;

  for(PHAsset *asset in collection) {
    [[PHImageManager defaultManager]
     requestImageForAsset:asset
     targetSize:CGSizeMake(80, 80)
     contentMode:PHImageContentModeAspectFill
     options:requestOptionForPhotos
     resultHandler:^(UIImage *result, NSDictionary *info) {
       tempData = UIImagePNGRepresentation(result);
       isFinished = YES;
     }];
  }
like image 536
siwymilek Avatar asked Nov 20 '22 10:11

siwymilek


1 Answers

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
         NSURL *assetUrl = [[NSURL alloc] initWithString:filepath];
         PHFetchResult *collection = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:assetUrl] options:nil];
         PHImageRequestOptions *requestOptionForPhotos = [[PHImageRequestOptions alloc] init];
         requestOptionForPhotos.networkAccessAllowed = YES;
         requestOptionForPhotos.synchronous = NO;

        __block BOOL isFinished = NO;
        __block NSData * tempData = nil;

       for (PHAsset *asset in collection) {
           [[PHImageManager defaultManager] 
                      requestImageForAsset:asset
                      targetSize:CGSizeMake(80, 80)
                      contentMode:PHImageContentModeAspectFill
                      options:requestOptionForPhotos
                      resultHandler:^(UIImage *result, NSDictionary *info) {
                           tempData = UIImagePNGRepresentation(result);
                           isFinished = YES;
           }];
       }
    });

try this code to get asynchronusly image and put breakpoint on result handdler to check weather you are getting image or not.

like image 109
Nirmit Dagly Avatar answered Dec 30 '22 07:12

Nirmit Dagly