J'ai essayé d'enregistrer et de charger des UIImages dans le dossier Documents de mon application ou de préférence dans le dossier temporaire (donc chaque fois que mon application est fermée, les images seront supprimées) mais elles ne fonctionnent pas correctement. J'ai essayé trois approches mais seule la troisième approche fonctionne et je me demande quelle est la bonne façon de le faire? J'apprécie hautement toute aide.Pourquoi la sauvegarde et le chargement des UIImages dans le dossier de documents ne fonctionnent pas correctement avec iOS 8+?
//First Approach, to save and load later, Doesn't work.
//Saving the image
NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask]
lastObject];
NSString*fileDirectoryStr = [[documentsDirectoryURL path] stringByAppendingPathComponent:@"E1BG.png"];
NSURL *url = [NSURL URLWithString:fileDirectoryStr];
//Saving either as Jpeg
[UIImagePNGRepresentation(finalFG) writeToFile:fileDirectoryStr atomically:YES];
//Or as PNG, because I need the transparent part to be kept transparent but non of them work.
[UIImageJPEGRepresentation(finalFG, 1.0) writeToFile:fileDirectoryStr atomically:YES];
//Loading image
UIImage *loadedBGImg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
//Returns nil
//Second approach.
//Saving the image
NSArray*pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsPath = [pathArray objectAtIndex:0];
NSString* fileDirectoryStr = [documentsPath stringByAppendingPathComponent:@"E1FG.png"];
//Again saving either as Jpeg
[UIImagePNGRepresentation(finalFG) writeToFile:fileDirectoryStr atomically:YES];
//Or as PNG, because I need the transparent part to be kept transparent but non of them work.
[UIImageJPEGRepresentation(finalFG, 1.0) writeToFile:fileDirectoryStr atomically:YES];
NSURL *url1 = [NSURL URLWithString:fileDirectoryStr];
//Loading image
UIImage *loadedImg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
//Third approach, Works but doesnt seem to be very efficient.
NSString *tmpDirectory = NSTemporaryDirectory();
//Save
NSString *tmpFileStrFG = [tmpDirectory stringByAppendingPathComponent:@"E1FG.png"];
NSURL *urlFG = [NSURL URLWithString:tmpFileStrFG];
NSData *imgDataFG = UIImagePNGRepresentation(finalFG);
[imgDataFG writeToURL:urlFG atomically:YES];
//Load
UIImage *ImggFG = [UIImage imageWithData: imgDataFG];
Vous souhaitez sauvegarder et récupérer l'image à partir du répertoire de documents. c'est ta question Correct? –
Non, je veux dire pourquoi les deux premières approches ne fonctionnent pas? Qu'est-ce que je fais mal? et suis-je bien dans la troisième approche pour utiliser le dossier temporaire dans mon application pour faire cela? @MikeAlter –
économiser pour l'approche de deux est bon. pls vérifier chercher l'URL pour le chargement de l'image et je ne suis pas sûr de l'approche un –