I am using this code to retrieve all images form my device but its not returning an result
- (void)viewDidLoad
{
[super viewDidLoad];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
NSLog(@"See Asset: %@", result);
[_assets addObject:result];
// Here storing the asset's image URL's in NSMutable array urlStoreArr
NSURL *url = [[result defaultRepresentation] url];
[_urlStoreArr addObject:url];
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if(group != nil)
{
[group enumerateAssetsUsingBlock:assetEnumerator];
}
};
_urlStoreArr = [[NSMutableArray alloc] init];
_assets = [[NSMutableArray alloc] init];
_library = [[ALAssetsLibrary alloc] init];
[_library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:assetGroupEnumerator
failureBlock: ^(NSError *error) {
NSLog(@"Failure");
}];
[self UploadImagesToServer];
}
-(void) UploadImagesToServer
{
for (int i=0; i<[_urlStoreArr count]; i++)
{
// To get the each image URL here...
NSString *str = [_urlStoreArr objectAtIndex:i];
NSLog(@"str: %@",str);
// Need to upload the images to my server..
}
}
You are using the
_urlStoreArrbefore it is initialized.When you are defining blocks, they take the current local value of variables that you use in the block.
So, in the
assetEnumeratorblock you are using_urlStoreArrbut you aren’t initialising it until later in the code.I’m assuming that
_urlStoreArris an iVar, since it has a leading underscore. If you are using ARC, then the iVar is initialised tonil, so yourassetEnumeratorblock is sending a message tonil. This is legal in Objective-C, but it just returnsnil.You have two options to fix this.
_urlStoreArr = [[NSMutableArray alloc] init];above the definition of theassetEnumeratorblock[_urlStoreArr addObject:url];try[self.urlStoreArr addObject:url];. This works because when using property access, you aren’t using the current value of_urlStoreArrat the time of definition, you are using the value at the time the block runs, which is after the iVar has been initialised.