2017-07-19 65 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) 
}