Previous: I am trying to get the number of photos in my camera roll, I started using blocks but have been having some difficulties.
Now: Here is my updated code, I am using async behavior but am returning a value before my block has a chance to complete.
#import "CoverViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
@interface CoverViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;
@property (assign) NSUInteger numberOfPhotos;
@end
@implementation CoverViewController
@synthesize CoverView;
- (void)viewWillAppear:(BOOL)animated
{
NSLog(@"viewWillAppear");
[self beginLoadingPhotoInfo];
}
//Photo collection info
- (void)beginLoadingPhotoInfo {
NSLog(@"loaded beginloadingphotoinfo");
__weak CoverViewController *__self = self;
[self PhotoCount:^(NSUInteger photoCount) {
__self.numberOfPhotos = photoCount;
}];
//[__self.CoverView reloadData];
}
- (void)PhotoCount:(void(^)(NSUInteger))completionBlock {
NSLog(@"photo count start");
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
__block NSInteger result = 0;
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop){
if(group != nil) {
NSLog(@"if");
result += [group numberOfAssets];
NSLog(@"enum: %d", result);
}
else {
NSLog(@"else");
//nil means we are done with enumeration
if (completionBlock) {
completionBlock(result);
}
}
};
[library enumerateGroupsWithTypes: ALAssetsGroupSavedPhotos
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(@"Problems");}
];
NSLog(@"result: %u", result);
}
// Layout of collection
//Number of cells in collection
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
NSLog(@"returned number: %d", self.numberOfPhotos);
return self.numberOfPhotos;
}
@end
I've added everything that is relevant in my coverviewcontroller.h file but the code seems to be loading before the block finishes. Here is my attempt to find the error and it shows that photoCount is returning 0 before my block finishes.
2013-07-27 21:16:00.986 slidr[1523:c07] viewWillAppear
2013-07-27 21:16:00.987 slidr[1523:c07] loaded beginloadingphotoinfo
2013-07-27 21:16:00.987 slidr[1523:c07] photo count start
2013-07-27 21:16:00.988 slidr[1523:c07] result: 0
2013-07-27 21:16:00.989 slidr[1523:c07] returned number: 0
2013-07-27 21:16:01.012 slidr[1523:c07] if
2013-07-27 21:16:01.013 slidr[1523:c07] enum: 3
2013-07-27 21:16:01.014 slidr[1523:c07] else
any ideas?