我从UIImagePickerController获取UIImage,并保存它:
- (void) saveImageLocally:(UIImage *)image {
NSData *imageData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"A5UserAvatar"]];
if (![imageData writeToFile:imagePath atomically:NO])
{
NSLog(@"Failed to cache image data to disk");
}
else
{
NSLog(@"the cachedImagedPath is %@", imagePath);
[[NSUserDefaults standardUserDefaults] setObject:imagePath forKey:@"AvatarKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
我可以在没有问题的情况下立即访问它:
- (UIImage *) getLocalImage {
NSString *path = [[NSUserDefaults standardUserDefaults] stringForKey:@"AvatarKey"];
NSLog(@"PATH FOR IMAGE IS %@", path);
if (path != nil) {
return [UIImage imageWithContentsOfFile:path];
} else {
return [UIImage imageNamed:@"default.gif"];
}
}
上面的代码完全没有问题地返回保存的UIImage。
问题是,当我杀死应用程序并再次启动它时,找不到图像! 我目前正在为iOS 7和8使用Xcode 6构建。我知道这个问题在模拟器中是不可避免的,但我也在现场设备上遇到它。
(见Xcode 6 keeps renaming my app's directory in iOS8 simulator after each run.)
我想知道我做错了什么,或者是否有另一种方法可以将任何图像作为文件存储在应用程序中,以便像化身一样使用。
答案 0 :(得分:1)
问题是您要保存完整路径而不是相对于Documents文件夹的路径。由于应用程序路径可以更改,因此无法保存完整路径。
你想要这样的东西:
- (void) saveImageLocally:(UIImage *)image {
NSData *imageData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:@"%@.png",@"A5UserAvatar"];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:filename];
if (![imageData writeToFile:imagePath atomically:NO])
{
NSLog(@"Failed to cache image data to disk");
}
else
{
NSLog(@"the cachedImagedPath is %@", imagePath);
[[NSUserDefaults standardUserDefaults] setObject:filename forKey:@"AvatarKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
- (UIImage *) getLocalImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [[NSUserDefaults standardUserDefaults] stringForKey:@"AvatarKey"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];
NSLog(@"PATH FOR IMAGE IS %@", path);
if (path != nil) {
return [UIImage imageWithContentsOfFile:path];
} else {
return [UIImage imageNamed:@"default.gif"];
}
}