ios - Swift - 如何从 json 获取数据类型

标签 ios json swift nsdate

我在后端使用 firebase,当我保存时间戳时,我将其另存为

let timeIntervalSince1970 = Date().timeIntervalSince1970 // 1563651621.760651
var dict = [String: Any]()
dict.updateValue(timeIntervalSince1970, forKey: "timeStamp")

ref.updateChildValues(dict)

稍后我解析它:

guard let dict = snapshot.value as? [String: Any] { else return }

let timeStamp = dict["timeStamp"] as? Double ?? 0 // 1563651621.760651

保存静默推送通知的日期时,我是这样保存的

let timeIntervalSince1970 = Date().timeIntervalSince1970 // 1563651621.760651
let date = Int64(timeIntervalSince1970 * 1000) // 1563651621760
dataDict.updateValue(date, forKey: "timeStamp")

// other values ...
paramDict.updateValue(dataDict, forKey: "data")

let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: paramDict, options: [.prettyPrinted])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in

        do {
            if let jsonData = data {
                if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                Print("Received data:\n\(jsonDataDict))")
            }
        }
    } catch let err as NSError {
        print(err.debugDescription)
    }
}
task.resume()

但是当我尝试从 userInfo 获取时间戳的数据类型时,我可以解析除日期之外的所有其他值:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    let info = notification.request.content.userInfo

    guard let userInfo = info as? [String: Any] else { return }

    for (k,v) in userInfo {
        print(k) // when k == timeStamp
        print(v) // the value printed is 1563651621760
    }

    let dbl = userInfo["timestamp"] as? Double ?? 0
    let nsn = userInfo["timestamp"] as? NSNumber ?? 0
    let fl = userInfo["timestamp"] as? Float ?? 0
    let in = userInfo["timestamp"] as? Int ?? 0
    let uin = userInfo["timestamp"] as? UInt ?? 0
    let in64 = userInfo["timestamp"] as? Int64 ?? 0
    print(dbl) // 0.0
    print(nsn) // 0
    print(fl) // 0.0
    print(in) // 0
    print(uin) // 0
    print(in64) // 0

如何获取数据类型以便解析日期(获取数据类型后我可以自己将其转换回 Date 对象)?

最佳答案

逻辑上如果不是数字类型就一定是字符串

let str = userInfo["timestamp"] as? String ?? ""

关于ios - Swift - 如何从 json 获取数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128070/

相关文章:

ios - SKNodes 之间的计算距离不会改变,尽管它们在移动

java - JSONObject 未正确创建

swift - 确保核心数据 @FetchRequest 变量动态运行需要哪些代码更改(附加代码)?

ios - 如何更改每日通知中的文本?

swift - 如何在 Swift 单元测试中断言可选 Bool 的值?

ios - EXC_BAD_ACCESS,使用NSZombies追踪

ios - 创建从容器 View 到 View Controller 的引用(IBOutlet)

ios - 无法使用iOS6设备存档应用

java - Gson错误: JsonSyntaxException when Json has a map

java - 如何在java中动态地从jsonArray填充数组