: 여기
import Firebase
import CodableFirebase
let item: GroceryItem = // here you will create an instance of GroceryItem
let data = try! FirebaseEncoder().encode(item)
Database.database().reference().child("pathToGraceryItem").setValue(data)
그리고 당신이 동일한 데이터를 읽을 방법 체재. 구조가 Decodable 또는 Codable을 준수해야합니다. SwiftyJSON으로이 작업을 수행했지만이 예제는 JSONSerialization을 사용하고 있으며 여전히 작동합니다.
JSONSnapshotPotatoes {
"name": "Potatoes",
"price": 5,
}
JSONSnapshotChicken {
"name": "Chicken",
"price": 10,
"onSale": true
}
struct GroceryItem: Decodable {
var name: String
var price: Double
var onSale: Bool? //Use optionals for keys that may or may not exist
}
Database.database().reference().child("grocery_item").observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? [String: Any] else { return }
do {
let jsonData = try JSONSerialization.data(withJSONObject: value, options: [])
let groceryItem = try JSONDecoder().decode(GroceryItem.self, from: jsonData)
print(groceryItem)
} catch let error {
print(error)
}
})
JSON 키가 Decodable 구조체와 다른 경우주의하십시오. CodingKeys를 사용해야합니다. 예 :
JSONSnapshotSpinach {
"title": "Spinach",
"price": 10,
"onSale": true
}
struct GroceryItem: Decodable {
var name: String
var price: Double
var onSale: Bool?
enum CodingKeys: String, CodingKey {
case name = "title"
case price
case onSale
}
}
자세한 내용은 Apple 문서 here을 참조하십시오.
Firebase에서 데이터를 가져올 때 JSONDecoder를 사용하지 마십시오. 대신 Firebase API를 사용해야합니다. –