2013-08-18 2 views
3

J'essaie d'enregistrer un fichier NsData dans un répertoire. qui est le code de ma méthode:NSdata writeToURL ne fonctionne pas

- (void)cacheImage:(NSData *)imageData withTitle:(NSString *)title 
{ 

    NSURL *cacheURL = (NSURL *)[[self.fileMenager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] objectAtIndex:0]; //we take the URL of the cache Directory and comvert the url of the cache directory into a string 
    NSURL *imageFolder = [cacheURL URLByAppendingPathComponent:PHOTO_CACHE_FOLDER]; 

    if ([self.fileMenager isWritableFileAtPath:[cacheURL path]]) { //check if the cache directory is writable 
     if (![self.fileMenager createDirectoryAtURL:cacheURL withIntermediateDirectories:NO attributes:nil error:nil]) { //check if the directory of our image is already exist 
      NSURL * fileToWrite = [[imageFolder URLByAppendingPathComponent:title isDirectory:NO] URLByAppendingPathExtension:@"jpg"]; //take the complete url of image 
      if ([imageData writeToURL:fileToWrite atomically:YES]) //atomically = safe write 
      { 
       NSArray *debug = [self.fileMenager contentsOfDirectoryAtPath:[imageFolder path] error:nil]; 
       for (NSURL *url in debug) 
        NSLog(@"url prooooo : %@",url); 
      } 
     } 
    } 
} 

qui est un exemple d'URL (fileToWrite) où je tente d'écrire:

file://localhost/Users/MarcoMignano/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/93B0A0AC-EC13-4050-88CA-F46FBA11001E/Library/Caches/image_cache/Mozart%201.jpg 

point est simple, la méthode writeToURL retour NON, je peux ne comprends pas pourquoi, l'URL semble correcte. Quelqu'un peut aider mon ' merci.

+0

Avez-vous débugué et voyez jusqu'où ça va? Est-ce que 'imageData' est non nul? – Wain

Répondre

2

Le problème principal est que vous créez le mauvais répertoire. Vous devez créer le répertoire imageFolder.

if ([self.fileManager createDirectoryAtURL:imageFolder withIntermediateDirectories:YES attributes:nil error:nil]) { 

et notez que vous ne voulez pas le ! dans la déclaration if.

+0

Utilisez le paramètre 'error' et enregistrez l'erreur résultante si' createDirectoryAtURL' renvoie NO. – rmaddy

+0

Parfait maintenant tout fonctionne très bien, mais j'ai eu supprimer l'application et le redémarrer à nouveau, sinon le createDirectoryAtURL retourner NON merci –