Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an ALAsset still exists using a URL

I've got an array containing ALAsset urls (not full ALAsset objects) So each time I start my application I want to check my array to see if it's still up to date...

So I tried

NSData *assetData = [[NSData alloc] initWithContentsOfFile:@"assets-library://asset/asset.PNG?id=1000000001&ext=PNG"];

but assetData is allways nil

thx for the help

like image 403
Mathieu Avatar asked Aug 28 '11 13:08

Mathieu


2 Answers

Use assetForURL:resultBlock:failureBlock: method of ALAssetsLibrary instead to get the asset from its URL.

// Create assets library
ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];

// Try to load asset at mediaURL
[library assetForURL:mediaURL resultBlock:^(ALAsset *asset) {
    // If asset exists
    if (asset) {
        // Type your code here for successful
    } else {
        // Type your code here for not existing asset
    }
} failureBlock:^(NSError *error) {
    // Type your code here for failure (when user doesn't allow location in your app)
}];
like image 85
Johnmph Avatar answered Oct 31 '22 08:10

Johnmph


Having assets path you can use this function to check if image exist:

-(BOOL) imageExistAtPath:(NSString *)assetsPath
{  
    __block BOOL imageExist = NO; 
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:[NSURL URLWithString:assetsPath] resultBlock:^(ALAsset *asset) {
        if (asset) {
            imageExist = YES;
            }
    } failureBlock:^(NSError *error) {
        NSLog(@"Error %@", error);
    }];
    return imageExist;
}

Remember that checking if image exist is checking asynchronyus. If you want to wait until new thread finish his life call function "imageExistAtPath" in main thread:

dispatch_async(dispatch_get_main_queue(), ^{
    [self imageExistAtPath:assetPath];
});

Or you can use semaphores, but this is not very nice solution:

-(BOOL) imageExistAtPath:(NSString *)assetsPath
{  
    __block BOOL imageExist = YES; 
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);   
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);   
    dispatch_async(queue, ^{  
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:[NSURL URLWithString:assetsPath] resultBlock:^(ALAsset *asset) {
            if (asset) {
                dispatch_semaphore_signal(semaphore); 
            } else {
                imageExist = NO;
                dispatch_semaphore_signal(semaphore); 
                }
        } failureBlock:^(NSError *error) {
             NSLog(@"Error %@", error);
        }];
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 
    return imageExist;
}
like image 21
edzio27 Avatar answered Oct 31 '22 09:10

edzio27