json - Swift - 来自字符串错误的日期

标签 json swift date swift3

我正在通过 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
    }
}

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

fatal error: unexpectedly found nil while unwrapping an Optional value

代码有什么问题?

谢谢。

最佳答案

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

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

在上一行中,如果日期值为 null 或使用不同的格式,它将崩溃

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

这里它可能会崩溃,因为消息来自字符串,但您正在转换为 int32 并且在 Appointment 实体中它被视为字符串并且对于 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)")
            }
        }

关于json - Swift - 来自字符串错误的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45189452/

相关文章:

Swift4 - Xcode 9 PCH 错误

javascript - 如何在从第一个日期选择器中选择日期时在第二个日期选择器中设置日期?

javascript - typescript :类型 'string' 不可分配给类型 '"数字"| "2-digit"' 在 Date::toLocaleDateString()

javascript - 从日期获取月份名称

ruby-on-rails - 在 Rails 应用程序中进行 JSON API 调用

ios - 在 Swift 5 中更改 Lottie AnimationView 大小

ios - 加载所有喜欢帖子的用户

iOS Swift 多维数组 - 编译需要很长时间。我应该改变什么?

c# - 如何使用 ASP.Net Web Api 2 进行部分响应

ios - 应用程序在iOS 10及更早版本上使用 “Could not instantiate class named _UIScrollViewLayoutGuide”崩溃