我正在构建一个2阶应用程序,一个供客户发布订单,另一个供司机接受,所以从另一个应用程序我无法访问用户ID,它几乎没有工作,但是处理Firebase是一件令人头疼的问题,现在我试图在我的数据结构中添加/读取新订单,但无法在不创建大量循环来筛选数据的情况下读取新订单的方法,所以当我检测到数据的变化时,我会删除所有内容并再次加载所有数据,
这是我的代码
override func viewDidLoad() {
super.viewDidLoad()
loadData()
ref.observe(.childChanged, with: { snapshot in
print("\n\n\nthe changed user is: \(snapshot.value)\n\n\n")
self.usrData.removeAll() //if change is detected, remove everything then readd them
self.loadData() //load firebase Data to my data structure
})
}
这是我的加载数据方法
func loadData(){
ref.observe(.childAdded, with: { snapshot in
if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
print("snapshot.value is snapshot \(snapshot.valueInExportFormat())")
if let tes = snapshot.value as? Dictionary<String, AnyObject> {
print("snapshot dictionarty is snapshot \(tes.reversed())")
let est = tes.reversed()
for t in est {
print("snapshot dictionarty name snapshot \(t.value["name"] as! String)")
print("snapshot dictionarty name snapshot \(t.value["email"] as! String)")
print("snapshot dictionarty name key \(t.key)")
let usr = userData(name: t.value["name"] as! String, email: t.value["email"] as! String, mobile: "", date: 0, latitude: "", longititude: "", ordertxt: "", status: "", usrKey:t.key, orderNumb:"")
self.usrData.append(usr)
}
}
var count = 0
for child in result {
let dict = child.childSnapshot(forPath: "orders").value as! Dictionary<String, AnyObject>
print("dict is \(dict)")
for dic in dict {
if (dic.value["status"] as! String) == "pending" {
self.usrData[count].mobile = dic.value["mobile"] as! String
self.usrData[count].date = dic.value["date"] as! NSNumber
self.usrData[count].latitude = dic.value["latitude"] as! String
self.usrData[count].longititude = dic.value["longitude"] as! String
self.usrData[count].ordertxt = dic.value["orderText"] as! String
self.usrData[count].status = dic.value["status"] as! String
self.usrData[count].orderNumb = dic.key
print("\(count) dic key is\(dic.key)")
} else {
print("\n\n\n status isn't pending for some reason -> \(self.usrData[count].status)")
self.usrData.remove(at: count)
count-=1
continue
}
}
count += 1
}
} else {
print("\n\n result is nil or something\n\n");
}
self.tableView.reloadData()
})
}
无论如何要改进它?
答案 0 :(得分:1)
你可以试试这个: -
users:{
userID1 :{...// DATA
ORDERS :{
orderID1 : true,
orderID2 : true,
orderID3 : true
}
},
userID1 :{...// DATA
ORDERS :{
orderID1 : true,
orderID2 : true,
orderID3 : true
}
},
userID1 :{...// DATA
ORDERS :{
orderID1 : true,
orderID2 : true,
orderID3 : true
}
}
orderes_Placed :{
orderID1 : {//order details},
orderID2 : {//order details},
}
}
您应该避免在NoSql数据结构中嵌套,并尝试尽可能地将其展平。当您浏览深度节点时,它会增加 带宽消耗
要收听添加到数据库节点的newData,只需在该节点启动一个侦听器( .observe(.childAdded ..)。
FIRDatabase.database().reference().child("orders_Placed").observe(.childAdded, with: {(Snapshot) in
print(Snapshot) // Will print out every new order that is placed via your app.
})