0

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.

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207

2 Answers2

1

Try to convert like this:

open static func formatDateToString(_ date : Date) -> String { 
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"

    return dateFormatter.string(from: date)
}
Pedro Pinho
  • 652
  • 3
  • 6
1

In given code there are two possibilities of crash

let appointmentDate = dateFormatter.date(from: jsonData["date"].string!)!

in above line it will crash if date value is null or different format then used

appointment.setValue(jsonData["message"].int32, forKey: "message")

here it may crash as message coming string but you are converting to int32 and in Appointment entity its taken as string and same for patient_name also

please check below update code

for(_,jsonData):(String, [String: Any]) in self.data["appointment"]["list"] {
            // Construct appointment date
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            var appointmentDate
            if let date = jsonData["date"].string {
                appointmentDate = dateFormatter.date(from: date) // possible crash may be date may be empty or or not given same date format which we used
            }
            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"], forKey: "message")// possible crash :: Here you are getting String converting to Int
            appointment.setValue(jsonData["patient_name"].int32, forKey: "patient_name")
            do {
                try moc.save()
            } catch {
                fatalError("\(error)")
            }
        }
Narayana Rao Routhu
  • 6,303
  • 27
  • 42