我有Firebase云结构:
如何捕获firstBook
和secondBook
的名称并写入数组
从firstbook
创建另一个带引号(Quote1 + Qoute2 + Quote3)的数组
我试试这个:
var array: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().ref?.child("category").child("book").observe(.value, with: { (snapshot) in
let valueCat = snapshot.value as! NSDictionary
let username = valueCat["name"] as? String ?? ""
print(username)
self.array.append(username)
}
}
到另一个阵列:
var quotAarray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().ref?.child("category").child("book").child("firstBook").observe(.value, with: { (snapshot) in
let valueCat = snapshot.value as! NSDictionary
let quote = valueCat["Quotes"] as? String ?? ""
print(quote)
self.quotAarray.append(quote)
}
}
答案 0 :(得分:0)
试试这个:
let valueCat = snapshot.value as! NSDictionary
if let firstBook = valueCat["firstBook"] as? NSDictionary {
print(firstBook["name"])
}
要获取所有书籍名称,您必须遍历孩子
答案 1 :(得分:0)
检查这是否有助于您根据收到的回复制作样本词典
使用的代码:
/// Sample Data on Base of your Output SHown
var DBData = [["firstBook":["Quotes": ["Quote1":111, "Quote2":222, "Quote3":333 ], "name":"first_Book"]], ["SecondBook":["Quotes":["Quote1":111,"Quote2":222,"Quote3":333],"name":"Second_Book"]]]
/// Names Array - In which book names need to be added
var nameArray = [String]()
/// For loop on base of DBData as it Array of Array Data
for i in 0..<DBData.count {
/// Assumed You have only one Main key in each array
/// Can be known before .
/// if you do not know Let's get keys here in Array at index i
let keysArray : [String] = Array(DBData[i].keys)
/// Now get the current dict value on base of key retrieved as in
/// first case its - firstBook
/// Second case its - SecondBook
let currentDictValue = DBData[i][keysArray[0]]
/// Now get Names of books
/// name is the key used in your DB its generic and its fixed
/// Now get value and add in Array
nameArray.append(currentDictValue!["name"] as! String)
}
/// Output
print("Name Array:\(nameArray)")
最终输出:
注意使用引号或引用,键在DB中应该类似
答案 2 :(得分:0)
@iOS Geek,但您的代码如何与Firebase一起使用?