Question

I'm using writeImageToSavedPhotosAlbum:orientation:completionBlock: to save an image and it's ok. Then I want an array of assets in the Album.

The first time I refresh my array it doesn't count the new image, while calling it a second time it works fine. Why? I understand that the writeImageToSavedPhotosAlbum start another thread and that the Block is called after the save operation completes, isn't it?

This is the code I use to save the image and refresh my array:

[_album refresh];
ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:image
                             metadata:metadataAsMutable
                      completionBlock:^(NSURL *assetURL, NSError *error) {
                                  if (error) {
                                      NSLog(@"ERROR: the image failed to be written");
                                  }
                                  else {
                                      NSLog(@"PHOTO SAVED - assetURL: %@", assetURL);
                                  }
                                  [_album refresh];
                                  [_album refresh];
                                  [spinner stopAnimating];
                                  [self close];
                              }];

This is the refresh function:

- (void)refresh {
    [_imgAssets removeAllObjects];
    if (_albumGroup) {
        [_albumGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if(result == nil) {
                NSLog(@"done enumerating photos (%d)", [_imgAssets count]);
                return;
            }
            [_imgAssets addObject:result];
            //NSLog(@">> enumerating photos (%d)", [_imgAssets count]);
        }];
    }
}

And this is what I obtain:

2013-06-04 23:19:07.962 PhotInfo[4835:c07] done enumerating photos (29)
2013-06-04 23:19:08.041 PhotInfo[4835:c07] PHOTO SAVED - assetURL: assets-library://asset/asset.JPG?id=CDC2E97A-FF47-4A52-99E2-574037155D92&ext=JPG
2013-06-04 23:19:08.042 PhotInfo[4835:c07] done enumerating photos (29)
2013-06-04 23:19:08.044 PhotInfo[4835:c07] done enumerating photos (30)

Moreover, if I replace the second of the 3 refresh with

[_album performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:YES];

it may or may not read the added image.

Where is the problem?

Thanks for the help.

Was it helpful?

Solution

I've resolved setting an observer on ALAssetsLibraryChangedNotification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top