Saving image into core data and fetching it into tableview cell

1.4k views Asked by At

I did a set up of CoreData with entity "users" and attribute "username" (when I type something in uitextfield it saves into core data and I got readings from core data into tableview cell). That is working like a charm. But I also want to display chosen picture from imagepickercontroller and that is also working fine when I choose picture but when I click save I think I got it saved. I don't know if it is saved because I eliminated all error so I got no errors, but it won't read that picture into tableview cell. I put new attribute "image" with type binary data into core data file but code does not work.

This is code for saving into core data

let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context)

newUser.setValue(nameField.text, forKey: "username")

let picture = UIImageJPEGRepresentation(photoImageView.image!, 1); 
newUser.setValue(picture, forKey: "image") 

And this is code where tableview reads data from core data

cell.imageView!.image = person.valueForKey("image") as? UIImage

I also tried with

[UIImage, imageWithData:self.myEvent.picture];

but Swift 2.0 don't have that syntax imageWithData

2

There are 2 answers

5
MirekE On

person.valueForKey("image") as? UIImage won't work.

Use UIImage(data:) to convert the retrieved NSData to UIImage.

0
Igy On

for retrieving image from core data i used this and it is finally working.

let image = person.valueForKey("image") as? NSData
    cell.imageView!.image = UIImage(data: image!)