2011-08-28 15 views
11

Ho un array contenente URL ALsset (non pieno di oggetti ALAsset) Quindi ogni volta che avvio la mia applicazione voglio controllare la mia matrice per vedere se è ancora fino a data ...Come verificare se esiste ancora un ALAsset usando un URL

Così ho provato

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

ma AssetData è allways nullo

thx per l'aiuto

risposta

21

Uso assetForURL: resultBl ock: failureBlock: metodo di ALAssetsLibrary invece di ottenere l'asset dal suo 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) 
}]; 
+1

Ok ma come faccio a tornare SI o NO? Scusa, non ho familiarità con i blocchi ... – Mathieu

+0

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

+0

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

7

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; 
} 
+2

Per quelli che inciampano su questo, credo che sia in realtà sbagliato. Come hai sottolineato, 'assetForURL: resultBlock: failureBlock': richiama i blocchi in modo asincrono, quindi molto probabilmente raggiungerà il' return imageExist' prima che il risultatoBlock sia stato invocato, e imageExist è sicuramente sempre NO. – jcaron

3

Per iOS 8 o versioni successive, esiste un metodo sincrono per verificare se esiste uno ALAsset.

@import Photos; 

if ([PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil].count) { 
    // exist 
} 

Swift:

import Photos 

if PHAsset.fetchAssetsWithALAssetURLs([assetURL], options: nil).count > 0 { 
    // exist 
} 

Swift 3:

import Photos 

if PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).count > 0 { 
    // exist 
} 
+0

questo mi aiuta a controllare se l'immagine esiste nella libreria di foto o meno. Mi piacerebbe condividere il codice di versione di Swift 2.0 di seguito. if (PHAsset.fetchAssetsWithALAssetURLs [[imageURL], options: nil) .count! = 0) –

+0

Anche questa soluzione funziona con risorse video? –

+1

@SalmanKhakwani Sì, dovrebbe funzionare. – user3480295

0

Utilizzare questo metodo per verificare se il file esiste

NSURL *yourFile = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:@"YourFileHere.txt"]; 

if ([[NSFileManager defaultManager]fileExistsAtPath:storeFile.path 
isDirectory:NO]) { 

    NSLog(@"The file DOES exist"); 

} else { 

    NSLog(@"The file does NOT exist"); 
} 
Problemi correlati