I'm using [ALAssetsLibrary enumerateGroupsWithTypes:] to store the ALAssets in an array. As this is an asynchronous operation, I need to wait for it to finish before continuing my work.
I read Cocoa thread synchronisation when using [ALAssetsLibrary enumerateGroupsWithTypes:] and tried the recommended NSConditionLock. However, the blocks are always performed in the main thread, thus if I wait using the conditionlock, the main thread is blocked and the blocks won't get executed -> I'm stuck. I even tried running the method loadAssets on a new thread, but still the blocks get executed on the main thread.
I can't find a way to actually wait for the enumeration to finish. Is there a way to force the blocks to a different thread than the main thread or anything else I can do?
Here's the code:
- (void)loadAssets
{
assets = [NSMutableArray array];
NSConditionLock *threadLock = [[NSConditionLock alloc] initWithCondition:THREADRUNNING];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if(result != nil)
{
[assets addObject:result];
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if(group != nil)
{
[group enumerateAssetsUsingBlock:assetEnumerator];
}
[threadLock lock];
[threadLock unlockWithCondition:THREADFINISHED];
};
void (^assetFailureBlock)(NSError *) = ^(NSError *error)
{
[threadLock lock];
[threadLock unlockWithCondition:THREADFINISHED];
};
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];
[threadLock lockWhenCondition:THREADFINISHED];
[threadLock unlock];
[assetsLibrary release];
[threadLock release];
}