使用核心数据保存图像
saving image with Core Data
我正在尝试使用 CoreData 保存用户个人资料图片,但不知道如何继续。
我知道我必须创建一个实体,而且我读到它必须是 BinaryData 类型,但后来我不明白如何保存和加载它。
我这样试过:
let profilePicture = UserPicture(context: AppDelegate.viewContext)
profilePicture.userProfilePicture = profilPictureImageView.image?.pngData()
try? AppDelegate.viewContext.save()
但是不起作用。
我没有找到任何足够清楚的帮助我。
要在 CoreData 中保存图像,您必须将图像转换为 DATA 类型,然后才能将其保存为 CoreData.This代码可能对在 CoreData 中保存图像有用。
@IBOutlet weak var profileimg: UIImageView?
let data = (profileimg?.image)!.pngData()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Entity", into: context!)
newUser.setValue(data, forKey: "img")
do {
try Constant.context?.save()
}
确保您输入的密钥正确。必须选中数据模型中允许外部存储的复选框 Inspector.But 我不建议将图像保存在 CoreData 中。希望这会有所帮助。
您可以将图像转换为字符串并将其存储在核心数据中。
self.selectedImage?.jpegData(compressionQuality: 1)?.base64EncodedString()
并使用此代码从核心数据加载图像
if let decodedData = Data(base64Encoded: todo.img as! String, options: .ignoreUnknownCharacters) {
let image = UIImage(data: decodedData)
Image(uiImage: image!)}
我正在尝试使用 CoreData 保存用户个人资料图片,但不知道如何继续。
我知道我必须创建一个实体,而且我读到它必须是 BinaryData 类型,但后来我不明白如何保存和加载它。
我这样试过:
let profilePicture = UserPicture(context: AppDelegate.viewContext)
profilePicture.userProfilePicture = profilPictureImageView.image?.pngData()
try? AppDelegate.viewContext.save()
但是不起作用。 我没有找到任何足够清楚的帮助我。
要在 CoreData 中保存图像,您必须将图像转换为 DATA 类型,然后才能将其保存为 CoreData.This代码可能对在 CoreData 中保存图像有用。
@IBOutlet weak var profileimg: UIImageView?
let data = (profileimg?.image)!.pngData()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Entity", into: context!)
newUser.setValue(data, forKey: "img")
do {
try Constant.context?.save()
}
确保您输入的密钥正确。必须选中数据模型中允许外部存储的复选框 Inspector.But 我不建议将图像保存在 CoreData 中。希望这会有所帮助。
您可以将图像转换为字符串并将其存储在核心数据中。
self.selectedImage?.jpegData(compressionQuality: 1)?.base64EncodedString()
并使用此代码从核心数据加载图像
if let decodedData = Data(base64Encoded: todo.img as! String, options: .ignoreUnknownCharacters) {
let image = UIImage(data: decodedData)
Image(uiImage: image!)}