Avendo percorso beni è possibile utilizzare questa funzione per controllare se l'immagine esiste:
-(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;
}
Si ricorda che la verifica se l'immagine esiste sta controllando asynchronyus. Se si vuole aspettare fino a nuovo thread finire la sua chiamata di vita funzione "imageExistAtPath" nel thread principale:
dispatch_async(dispatch_get_main_queue(), ^{
[self imageExistAtPath:assetPath];
});
oppure è possibile utilizzare i semafori, ma questo non è molto bella soluzione:
-(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;
}
Ok ma come faccio a tornare SI o NO? Scusa, non ho familiarità con i blocchi ... – Mathieu
Puoi dirmi cosa vuoi fare? Questi blocchi sono chiamati in modo asincrono, quindi invece di restituire un valore, dovresti invece inserire il codice che ha bisogno della risorsa in un metodo e chiamare questo metodo nel blocco o puoi inserire il codice direttamente nel blocco. – Johnmph
Voglio eseguire il loop sul mio array di assetUrl per verificare se la risorsa esiste ancora e se non voglio rimuoverla dall'elenco ed eliminare i file memorizzati nella cache – Mathieu