Question

I'm working on photo app and here is the deal:

I have created custom photo album an added some photos to it (users can create many albums). I used ALAssetsLibrary for this and CustomPhotoAlbum category. Everything worked flawlessly until I needed to get those photos back to reuse them. So Ive created custom metod for this category and I'm saving UIImages to NSMutableArray but I want this method to return this array outside... My problem is that enumerateAssetsUsingBlock: is running in background and saving photos to album while I want to access them! How can I do something for this method to wait until every photo is loaded to album and then return NSArray?

Here is my method:

 - (void)loadImagesFromAlbumNamed:(NSString *)name
{
    NSMutableArray *photos = [[NSMutableArray alloc] init];

    [self enumerateGroupsWithTypes:ALAssetsGroupAll
                        usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                            if (group == nil) {
                                return;
                            }

                            if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:name]) {
                                [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                                    if (result == nil) {
                                        return;
                                    }

                                    // NSLog(@"%@", result);
                                    UIImage *image = [UIImage imageWithCGImage:(__bridge CGImageRef)([result defaultRepresentation])];
                                    [photos addObject:image];
                                }];
                                NSLog(@"%@", [photos description]);
                            }
                        } failureBlock:^(NSError *error) {
                            NSLog(@"%@", [error localizedDescription]);
                        }];
}

I hope you get my point of view... If not, just ask and I'll try to explain it better way!

Was it helpful?

Solution

Don't try to wait. Instead, pass a block to your method which should be called when all of the asset processing blocks are completed and will pass the array of images back to the caller. The caller should not block, you just want to structure your method to deal with the asynchronous nature of what you're trying to do.

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