I am fetching JSON objects via RESTFUL API and inserting into core-data entity.
One such entity is Appointment, here is my entity property
extension Appointment {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Appointment> {
return NSFetchRequest<Appointment>(entityName: "Appointment");
}
@NSManaged public var date: Date?
@NSManaged public var id: Int32
@NSManaged public var message: String?
@NSManaged public var patient_name: String?
@NSManaged public var doctor: Doctor?
}
Here is the code I am using to insert the entity
for(_,jsonData):(String, JSON) in self.data["appointment"]["list"] {
// Construct appointment date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let appointmentDate = dateFormatter.date(from: jsonData["date"].string!)!
print(appointmentDate)
// Preare appointment entity for inserting
let appointment = NSEntityDescription.insertNewObject(forEntityName: "Appointment", into: moc)
appointment.setValue(jsonData["id"].int32, forKey: "id")
appointment.setValue(appointmentDate, forKey: "date")
appointment.setValue(jsonData["message"].int32, forKey: "message")
appointment.setValue(jsonData["patient_name"].int32, forKey: "patient_name")
do {
try moc.save()
} catch {
fatalError("\(error)")
}
}
And here is the related JSON I get from the API
"appointment": {
"list": {
"id": 1,
"date": "2017-07-03 17:30",
"message": "Some message is usefule here",
"patient_name": "John Doe",
"doctor_id": 4
}
}
But when I run the code, I get the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
What is wrong with the code?
Thanks.