使用UserDefaults终止时坚持应用

时间:2019-01-01 05:36:19

标签: ios swift persistence nsuserdefaults

我想使用userdefaults保存图像,我想要实现的是在更改图像并终止应用程序之后。图像用户更改仍然存在。如何使用userdefaults实现此目的。

这是我的代码,当用户选择图像并将其保存在userdefaults中

var data: Data? //I make a reference data to save imageData in pickerController
@objc func handleImagePicker() {
    let imagePickerController = UIImagePickerController()
    imagePickerController.allowsEditing = true
    imagePickerController.sourceType = .photoLibrary
    imagePickerController.delegate = self

    present(imagePickerController, animated: true)
}

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let editedImage = info[.editedImage] as? UIImage {
        guard let imageData = editedImage.jpegData(compressionQuality: 0.5) else { return }
        self.data = NSKeyedArchiver.archivedData(withRootObject: imageData)
        UserDefaults.standard.set(data, forKey: "profileImageEditedKey")
        UserDefaults.standard.synchronize()
        profileImageView.image = editedImage.withRenderingMode(.alwaysOriginal)
    } else if let originalImage = info[.originalImage] as? UIImage {
        guard let imageData = originalImage.jpegData(compressionQuality: 1) else { return }
        self.data = NSKeyedArchiver.archivedData(withRootObject: imageData)
        UserDefaults.standard.set(data, forKey: "profileImageOriginalKey")
        UserDefaults.standard.synchronize()
        profileImageView.image = originalImage.withRenderingMode(.alwaysOriginal)
    }
    dismiss(animated: true)
}

这是我在应用终止后获取数据时放置在viewWillAppear中的代码

private func fetchData() {
    guard let data = data else { return }
    guard let image = NSKeyedUnarchiver.unarchiveObject(with: data) as? UIImage else { return }

    profileImageView.image = image.withRenderingMode(.alwaysOriginal)
    print("fetch...")
}

1 个答案:

答案 0 :(得分:1)

  1. Data中保存大数据不是一个好主意,通常不建议这样做,因为它不是保存图像的最有效方法;一种更有效的方法是将图像保存在应用程序的“文档目录”中。您可以使用write UserDefaults函数来做到这一点。 还有其他第三个库。

  2. 如果您坚持使用guard let imageData = editedImage.jpegData(compressionQuality: 0.5) else { return } UserDefaults.standard.set(imageData, forKey: "profileImageEditedKey") UserDefaults.standard.synchronize()

    保存图像

    UserDefaults

    guard let data = UserDefaults.standard.object(forKey: "profileImageOriginalKey") as? Data else { return; } let image = UIImage.init(data: data);

    获取图像
    str_replace