一尘不染

是否要在NSUserDefaults中保存图像?

swift

是否可以将图像另存NSUserDefaults为对象,然后检索以供进一步使用?


阅读 236

收藏
2020-07-07

共1个答案

一尘不染

注意! 如果您要在iOS8 / XCODE6以下工作,请参阅下面的更新

对于仍在寻找答案的用户,这里提供了“建议”方式的代码,用于将图像保存在NSUserDefaults中。您不应该将图像数据直接保存到NSUserDefaults中!

写入数据:

// Get image data. Here you can use UIImagePNGRepresentation if you need transparency
NSData *imageData = UIImageJPEGRepresentation(image, 1);

// Get image path in user's folder and store file with name image_CurrentTimestamp.jpg (see documentsPathForFileName below)
NSString *imagePath = [self documentsPathForFileName:[NSString stringWithFormat:@"image_%f.jpg", [NSDate timeIntervalSinceReferenceDate]]];

// Write image data to user's folder
[imageData writeToFile:imagePath atomically:YES];

// Store path in NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:imagePath forKey:kPLDefaultsAvatarUrl];

// Sync user defaults
[[NSUserDefaults standardUserDefaults] synchronize];

读取数据:

NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:kPLDefaultsAvatarUrl];
if (imagePath) {
    self.avatarImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
}

documentsPathForFileName:

- (NSString *)documentsPathForFileName:(NSString *)name {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    return [documentsPath stringByAppendingPathComponent:name];
}

对于iOS8 / XCODE6 正如以下注释中提到的tmr和DevC,xcode6 / ios8存在问题。xcode5和xcode
6安装过程之间的区别在于,xcode6 在每次在xcode中运行 应用程序更改应用程序UUID
(请参阅路径中突出显示的部分:/ var / mobile / Containers / Data / Application /
B0D49CF5-8FBE-4F14-87AE-FA8C16A678B1 / Documents / image.jpg)。

因此,有两种解决方法:

  1. 跳过此问题,因为一旦将应用程序安装在真实设备上,它就永远不会更改UUID(事实上,它确实可以更改,但它是新应用程序)
  2. 将相对路径保存到所需文件夹(在本例中为应用程序的根目录)

这是快速版本的代码,作为奖励(使用第二种方法):

写入数据:

let imageData = UIImageJPEGRepresentation(image, 1)
let relativePath = "image_\(NSDate.timeIntervalSinceReferenceDate()).jpg"
let path = self.documentsPathForFileName(relativePath)
imageData.writeToFile(path, atomically: true)
NSUserDefaults.standardUserDefaults().setObject(relativePath, forKey: "path")
NSUserDefaults.standardUserDefaults().synchronize()

读取数据:

let possibleOldImagePath = NSUserDefaults.standardUserDefaults().objectForKey("path") as String?
if let oldImagePath = possibleOldImagePath {
    let oldFullPath = self.documentsPathForFileName(oldImagePath)
    let oldImageData = NSData(contentsOfFile: oldFullPath)
    // here is your saved image:
    let oldImage = UIImage(data: oldImageData)
}

documentsPathForFileName:

func documentsPathForFileName(name: String) -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
    let path = paths[0] as String;
    let fullPath = path.stringByAppendingPathComponent(name)

    return fullPath
}
2020-07-07