ios - Swift - 无法将核心数据转换为 url 参数
问题描述
我正在尝试构建一个跟踪设备位置的小应用程序。所以将位置保存到核心数据中。但无法将其转换为 json 以将此信息发送到服务器。我收到以下错误
2018-12-18 13:08:33.583580+0530 我的应用程序[6696:144278] [常规] 引发了未捕获的异常。
2018-12-18 13:08:33.583605+0530 我的应用程序 [6696:144278] [常规] JSON 写入 (__NSDate) 中的类型无效。
2018-12-18 13:08:33.604814+0530 我的应用程序[6696:144278] [常规] (0 CoreFoundation 0x00007fff4af112db __exceptionPreprocess + 171 ........)
从核心数据加载数据
func loadingFromCoreData() -> [String:Dictionary<String,AnyObject>]
{
var locationsArray: [String:Dictionary<String,AnyObject>] = [:]
var count = 0
if let context = (NSApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
do {
locationDataInstance = try context.fetch(LocationInformation.fetchRequest())
} catch {
}
}
print("IN Loading From database")
for locationDI in locationDataInstance {
var location_info: [String:AnyObject]=[:]
location_info["latitude"] = locationDI.latitude as AnyObject
location_info["longitude"] = locationDI.longitude as AnyObject
location_info["timestamp"] = locationDI.timestamp as AnyObject
locationsArray["\(count)"] = location_info
count = count + 1
}
return locationsArray
}
字典到 Json 覆盖
let parameters:Dictionary<String,AnyObject> = ["name":devicename as AnyObject,"loctioninfo":loadingFromCoreData() as AnyObject]
do {
let js = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
print(js)
} catch {
print(error.description)
}
解决方案
错误很明显: 的类型timestamp
显然是Date
并且 JSON 不支持这种类型。
例如,添加计算属性以将Date
对象转换为 UNIX 时间戳或日期字符串
var unixTimeStamp : Double {
return timestamp.timeIntervalSince1970
}
as AnyObject
并通过将字典声明为来摆脱这种丑陋的演员阵容[String:Any]
推荐阅读
- c - 在 C 中创建动态数组而不指定最大大小
- android - Timer() fixedRateTimer 设置为 20 秒不会在触发 onStop 时停止
- javascript - 如何从外部 nodemailer 传输访问 info.response 对象
- c - C 中的程序显示错误结果,奇数
- java - 如何在数组中添加前缀 0?
- asp.net-core - Asp.net core 2.2 api 无法集成 miniprofiler、dapper 和 mySql 工作
- python - 无法在中间模型中将 null 保存到 ForeignKey - Django
- dask - 使用 Dask 从多个 Python 进程编写 Parquet 文件
- c - 内核模块中已定义但未使用的变量消息
- r - 在 RStudio 中显示或呈现 html 的一般方法(就像在浏览器中一样)?