如何将拾取的图像添加到核心数据中

时间:2016-10-31 15:15:29

标签: swift xcode swift3 xcode8

我是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)
}

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

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

1 个答案:

答案 0 :(得分:0)

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

let img = imageView.image

let imgData = UIImageJPEGRepresentation(img!, 1)

我希望这会有用。