Can Swift 4's JSONDecoder be used with Firebase Realtime Database?

后端 未结 7 1783
有刺的猬
有刺的猬 2020-12-28 19:39

I am trying to decode data from a Firebase DataSnapshot so that it can be decoded using JSONDecoder.

I can decode this data fine when I use a URL to access it with a

7条回答
  •  醉酒成梦
    2020-12-28 20:19

    If your data type is Codable you can use the following solution to decode directly. You do not need any plugin. I used the solution for Cloud Firestore.

    import Firebase
    import FirebaseFirestoreSwift
    
    
    let db = Firestore.firestore()
    let query = db.collection("CollectionName")
                .whereField("id", isEqualTo: "123")
    
    guard let documents = snapshot?.documents, error == nil else {
        return
    }
    
    if let document = documents.first {
        do {
            let decodedData = try document.data(as: ModelClass.self) 
            // ModelClass a Codable Class
    
        }
        catch let error {
            // 
        }
    }
    

提交回复
热议问题