首页 > 解决方案 > 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)
    }

标签: iosswiftcocoacore-data

解决方案


错误很明显: 的类型timestamp显然是Date并且 JSON 不支持这种类型。

例如,添加计算属性以将Date对象转换为 UNIX 时间戳或日期字符串

var unixTimeStamp : Double {
    return timestamp.timeIntervalSince1970
}

as AnyObject并通过将字典声明为来摆脱这种丑陋的演员阵容[String:Any]


推荐阅读