I have a method which returns a boolean value. It should return true if at least one image/asset has been found from a URL. The code is as shown below. Inside the block when i print the count of objects in the array, it prints properly. However, outside the block, the count is zero and it does not enter the if block and the method always returns FALSE. I guess this happens because the function is returning before the block is being executed. How do I tackle this issue? How do I ensure that the method returns true if atleast one URL has been added to self.imageURLs inside the block?
-(BOOL)getPhotos
{
self.imagesFound = FALSE;
//get all image url's from database
//for each row returned do the following:
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *URLString = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSURL *imageURL = [NSURL URLWithString:URLString];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:imageURL resultBlock:^(ALAsset *asset)
{
if (asset) {
//if an image exists with this URL, add it to self.imageURLs
[self.imageURLs addObject:URLString];
NSLog(@"no. of objects in array: %lu", (unsigned long)self.imageURLs.count);
}
}
failureBlock:^(NSError *error)
{
// error handling
NSLog(@"failure-----");
}];
}
if (self.imageURLs.count > 0) {
NSLog(@"self.imageURLs count = %lu", (unsigned long)self.imageURLs.count);
self.imagesFound = TRUE;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Sorry!" message:@"No photos found" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
return self.imagesFound;
}