Search code examples
objective-cphotos

Array to saved photos always returned as empty


I am trying to create an array of all images from the saved photo album that match a certain criteria. Here is a simplified code for it. I add the photos to myImages array and confirmed via the "Added Image" log that the right images get logged. However the array returned by the function is always empty. Fairly new to Objective-C so any suggestions would be helpful.

NSMutableArray * myImages = [NSMutableArray array];

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

// Enumerate just the photos by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

    // Within the group enumeration block, filter to enumerate just photos.
    [group setAssetsFilter:[ALAssetsFilter allPhotos]];

    [group enumerateAssetsUsingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {

                             // The end of the enumeration is signaled by asset == nil.
                             if (alAsset) {
                                 ALAssetRepresentation *representation = [alAsset defaultRepresentation];
                                 UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullResolutionImage]];

                                     NSLog(@"Added Image");
                                     [myImages addObject:latestPhoto];
                             }
                         }];
                    }
                     failureBlock: ^(NSError *error) {
                         // Typically you should handle an error more gracefully than this.
                         NSLog(@"No groups");
                     }];

return myImages;

Solution

  • What is imagesTakenOnDate? Is that supposed to be myImages? If so, you cannot return it in this manner as the block code will execute after the method returns. The method is asynchronous. Rather than "return" you have 2 options to be able to access the modified array outside the function:

    option 1: make your method take a completion block as a parameter, and then call the completion block inside the enumerateGroupsWithTypes block, and pass the completion block the array. For example:

    typedef void (^CompletionBlock)(id, NSError*);
    -(void)myMethodWithCompletionBlock:(CompletionBlock)completionBlock;
    

    then when you're done with success call:

    completionBlock(myImages, nil);
    

    and in the failureBlock call:

    completionBlock(nil, error);
    

    option 2: make the array an ivar that is retained on your parent object, rather than a local variable, and then declare it as a __block variable so it can be modified within the block.