【问题标题】:Swift - Date From String ErrorSwift - 来自字符串错误的日期
【发布时间】:2017-07-19 11:40:09
【问题描述】:

我正在通过 RESTFUL API 获取 JSON 对象并插入到核心数据实体中。

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

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

这是我从 API 获得的相关 JSON

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

但是当我运行代码时,我得到以下错误:

致命错误:在展开可选值时意外发现 nil

代码有什么问题?

谢谢。

【问题讨论】:

  • 在调用date()之前尝试将语言环境设置为您的dateFormatter
  • 与此处相同的问题:stackoverflow.com/questions/40692378/…?
  • 我认为问题出在 letointmentDate = dateFormatter.date(from: jsonData["date"].string! 你正在添加的地方可能是 nil。你确定每个 json 对象你的 json 响应有日期吗?
  • 我可以假设您在处理数据后正在获取数据。
  • 是的,问题出在数据解析上,因为索引操作错误。修复它解决了我的问题

标签: json swift date swift3


【解决方案1】:

在给定的代码中有两种可能的崩溃

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

在上面的行中,如果日期值为 null 或使用不同的格式,则会崩溃

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

在这里它可能会作为消息来的字符串而崩溃,但您正在转换为 int32 并且在 Appointment 实体中它被视为字符串,并且对于患者姓名也相同

请查看下方更新代码

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

【讨论】:

    【解决方案2】:

    尝试像这样转换:

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

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多