2017-07-19 64 views
0

我通过RESTFUL API获取JSON对象并插入到核心数据实体中。Swift - 从字符串错误日期

一个这样的实体是约会,这是我的实体属性

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? 

} 

这里是我使用插入实体

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)") 
    } 
} 

而且这里的代码相关的JSON我从一开始API

"appointment": { 
    "list": { 
     "id": 1, 
     "date": "2017-07-03 17:30", 
     "message": "Some message is usefule here", 
     "patient_name": "John Doe", 
     "doctor_id": 4 
    } 
} 

但是当我运行代码时,出现以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

代码有什么问题?

谢谢。

+0

尝试设置区域设置你的' dateFormatter'在调用'date()'之前 –

+0

与此处相同的问题:https://stackoverflow.com/questions/40692378/dateformatter-doesnt-return-date-for-hhmmss? –

+0

我认为问题在于让appointmentDate = dateFormatter.date(来自:jsonData [“date”]。string!你正在添加!它可能是nil。你确定你的json响应的每个json对象都有日期吗? –

回答

1

在给定的代码有在上述行崩溃

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

的两种可能性,如果日期值为null或则不同的格式使用它会崩溃

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

这可能会崩溃的消息,未来字符串,但要转换为int32,并在其作为字符串,并同为patient_name约会实体也

请检查下面的更新代码

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)") 
      } 
     } 
1

尝试转换是这样的:

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

    return dateFormatter.string(from: date) 
}