簡體   English   中英

Swift-如何從JSON獲取數據類型

[英]Swift -How to get datatype from json

我將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 ?? ""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM