H.N. H.N. - 1 month ago 14
Swift Question

How can I add a picked image into core data

I am a new guys on swift 3 (xcode) and I am working on a project.

I am building a data base with core data, and inserting data in there.

Now in this project a user can choose a picture in his device and than I should save it into core data.

I have this so far:

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 {

}



}


I am making the user choose a photo with a 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)
}


Now, something is missing I know. How can I make the user save his picked image into core data like this?

Should I get the url of choosed image? I tried but couldnt :( Or is there a better solution?

Answer

Instead of getting image from UIImagePickerControllerReferenceURL as! NSURL. You can get the image from imageView. Then you can convert that image into NSData to store in core data.

let img = imageView.image

let imgData = UIImageJPEGRepresentation(img!, 1)

I hope this will be useful.

Comments