Reputation: 1041
I have a core data app(like a Diary) in which I prompt user to pick an image from Camera or Photo Library and set it to ImageData and then to the button's image. This part works but if user doesnt choose image and just write the text and press Done. It gives me "unexpectedly found nil" error. I have ann image named "icn_noimage" so if user hasnt selected any image, this image will be set to button. I tried to do it this way: Here, imageData, body, date are attributes of core data.
var pickedImage: UIImage! {
didSet {
if (pickedImage == nil) {
self.imageButton?.setImage(UIImage(named: "icn_noimage"), forState: .Normal)
} else {
self.imageButton?.setImage(pickedImage, forState: .Normal)
}
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image: UIImage! = info[UIImagePickerControllerOriginalImage] as! UIImage
self.pickedImage = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func insertDiaryEntry() {
let coreDataStack: CoreDataStack = CoreDataStack.defaultStack
let entry: DiaryEntry = NSEntityDescription.insertNewObjectForEntityForName("DiaryEntry", inManagedObjectContext: coreDataStack.managedObjectContext) as! DiaryEntry
entry.body = self.textView.text
entry.date = NSDate().timeIntervalSince1970
entry.mood = self.pickedMood!.rawValue
entry.imageData = UIImageJPEGRepresentation(self.pickedImage, 0.75)
entry.location = self.location as String
coreDataStack.saveContext()
}
In case, I have been unable to explain my question, please ask the details. Appreciate your help.....
Upvotes: 1
Views: 299
Reputation: 14514
Make sure "icn_noimage"
image available in your bundle.
And still mark imageData
as Optional in DiaryEntry
class.
Use imageData with Optional(?) , imageData?
.
This will accept nil value of image Data in case image not available.
If it is already optional then use conditional Un-wrapping.
if let image = self.pickedImage
{
let imageData = UIImageJPEGRepresentation(image, 0.75)
entry.imageData = imageData
}
Upvotes: 1