首页 > 解决方案 > 致命异常:使用格式化程序将字符串转换为日期时出现 NSInternalInconsistencyException

问题描述

我在使用 ISO8601DateFormatter 和 formatOptions.withFractionalSeconds来解析这样的字符串时收到 Crashlytics 崩溃报告

2017-01-23T10:12:31Z

或者

2017-01-23T10:12:31.484Z

或者

2017-01-23T10:12:31.484221Z

迄今为止,此代码:

if #available(iOS 11.0, *) {
  let formatter = ISO8601DateFormatter()
  formatter.formatOptions.insert(.withFractionalSeconds)
  result = formatter.date(from: string)
}

我收到的崩溃消息是:

致命异常:NSInternalInconsistencyException

无效参数不满足:formatOptions == 0 || !(formatOptions & ~(NSISO8601DateFormatWithYear | NSISO8601DateFormatWithMonth | NSISO8601DateFormatWithWeekOfYear | NSISO8601DateFormatWithDay | NSISO8601DateFormatWithTime | NSISO8601DateFormatWithTimeZone | NSISO8601DateFormatWithSpaceBetweenDateAndTime | NSISO8601DateFormatWithDashSeparatorInDate | NSISO8601DateFormatWithColonSeparatorInTime | NSISO8601DateFormatWithColonSeparatorInTimeZone | NSISO8601DateFormatWithFullDate | NSISO8601DateFormatWithFullTime | NSISO8601DateFormatWithInternetDateTime))

标签: swiftexceptioncrashios11dateformatter

解决方案


似乎此崩溃是由.withFractionalSecondsiOS 11.0.* 和 11.1.* 中的选项引起的。

要解决此问题,您应该更改#available(iOS 11.0, *)#available(iOS 11.2, *)

更多细节:

虽然 structISO8601DateFormatter.Options自 iOS 10.0+ 起可用,并且选项本身static var withFractionalSeconds: ISO8601DateFormatter.Options { get }自 iOS 11.0+ 起可用。在这里这里阅读

使用选项 .withFractionalSeconds “崩溃到 11.2。它在 11.2+ 中已修复”。关于这个评论


推荐阅读