简体   繁体   中英

Swift -How to get datatype from json

I use firebase for backend and when I save the timestamp I save it as

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

ref.updateChildValues(dict)

later I parse it:

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

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

When saving the date for a silent push notification I save it like this

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()

But when I try to get the data type for the timestamp from userInfo I can parse all the other values except the date:

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

How can I get the data type so I can parse the date (once I get the data type I can convert it back to a Date object on my own)?

逻辑上,如果它不是数字类型,则必须是字符串

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM