gpt4 book ai didi

swift - 如何将选取的图像添加到核心数据中

转载 作者:行者123 更新时间:2023-11-30 12:56:27 25 4
gpt4 key购买 nike

我是 swift 3 (xcode) 的新人,我正在开发一个项目。

我正在使用核心数据构建一个数据库,并在其中插入数据。

现在在这个项目中,用户可以在他的设备中选择一张图片,然后我应该将其保存到核心数据中。

到目前为止我有这个:

   func addUser() {

let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

request.returnsObjectsAsFaults = false


let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)


if (firstName.text == "" && lastName.text == "" && contact.text == "" && email.text == "") { //if we have a user profile delete it
deleteUser()

} else { //add a new user profile

newUser.setValue(firstName.text, forKey: "firstName")
newUser.setValue(lastName.text, forKey: "lastName")
newUser.setValue(contact.text, forKey: "contact")
newUser.setValue(email.text, forKey: "email")


let imgUrl = UIImagePickerControllerReferenceURL as! NSURL

print(imgUrl) //should print selected photo however not doing it


//Saving image
let img = UIImage(named: "imgUrl")

let imgData = UIImageJPEGRepresentation(img!, 1)

newUser.setValue(imgData, forKey: "photo")




print ("Data added in Users")

}

do {

try context.save()

} catch {

}



}

我让用户使用 UIImagePickerController 选择照片:

 @IBAction func addPhoto(_ sender: UIButton) {

let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary

image.allowsEditing = false

self.present(image, animated: true)
{


}

}

//image adding - galery
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
imageView.image = image

}

self.dismiss(animated: true, completion: nil)
}

现在,我知道缺少了一些东西。如何让用户将他选择的图像保存到像这样的核心数据中?

我应该获取所选图像的网址吗?我尝试过但不能:(或者有更好的解决方案吗?

最佳答案

而不是从 UIImagePickerControllerReferenceURL 获取图像! NSURL。您可以从imageView获取图像。然后您可以将该图像转换为 NSData 以存储在核心数据中。

let img = imageView.image

let imgData = UIImageJPEGRepresentation(img!, 1)

我希望这会有用。

关于swift - 如何将选取的图像添加到核心数据中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40345099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com