데이터를 Firebase에 dictionary형태로 writing해보겠습니다.
서점에서 고객관리 데이터를 넣고싶다고 가정 해보면
override func viewDidLoad() {
super.viewDidLoad()
saveCustomers()
}
//saveCustomer()호출
func saveCustomers() {
let books = [Book(title: "BbiDdiBaBiDiBu", author: "Chul"), Book(title: "Machine", author: "Young")]
let customer1 = Customer(id: "\(Customer.id)", name: "ChaSsi", books: books)
Customer.id += 1
let customer2 = Customer(id: "\(Customer.id)", name: "Ming", books: books)
Customer.id += 1
let customer3 = Customer(id: "\(Customer.id)", name: "DDong", books: books)
Customer.id += 1
//db에 write
db.child("customers").child(customer1.id).setValue(customer1.toDictionary)
db.child("customers").child(customer2.id).setValue(customer2.toDictionary)
db.child("customers").child(customer3.id).setValue(customer3.toDictionary)
}
struct Customer {
let id: String // static var id와 차이
let name: String
let books: [Book]
var toDictionary: [String: Any] {
let booksArrary = books.map { $0.toDictionary }
let dict: [String: Any] = ["id": id, "name": name, "books": booksArrary]
return dict
}
static var id: Int = 0
}
//고객 structure
struct Book {
let title: String
let author: String
var toDictionary: [String: Any] {
let dict: [String: Any] = ["title": title, "author": author]
return dict
}
}
//책 structure
결과
서버에 잘 들어간 것을 확인 할 수 있었습니다.~
'iOS > Swift 어플 따라하기' 카테고리의 다른 글
[Swift] Firebase Realtime Database에서 update, delete (0) | 2022.04.04 |
---|---|
[Swift] Firebase Realtime Database에서 Parsing Data (0) | 2022.04.03 |
[Swift] Firebase Realtime Database에서 Read Data (0) | 2022.04.02 |
[swift] SDK? / cocoapods 설치 (0) | 2022.03.31 |
[Swift] PlayerView가로모드/ ViewController를 띄웠을 때/preview자동플레이/재생,정지버튼 (0) | 2022.03.30 |