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

后端 未结 7 1793
有刺的猬
有刺的猬 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:31

    Or you can use this solution for children

    extension DatabaseReference {
      func makeSimpleRequest(completion: @escaping (U) -> Void) {
        self.observeSingleEvent(of: .value, with: { snapshot in
            guard let object = snapshot.children.allObjects as? [DataSnapshot] else { return }
            let dict = object.compactMap { $0.value as? [String: Any] }
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [])
                let parsedObjects = try JSONDecoder().decode(U.self, from: jsonData)
                completion(parsedObjects)
            } catch let error {
                print(error)
            }
        })
      }
    }
    

    and use

    self.refPriceStatistics.child(productId).makeSimpleRequest { (parsedArray: [YourArray]) in
        callback(parsedArray)
    }
    

提交回复
热议问题