0
根據Firebase Docs,childByAutoId
只要調用它就應該生成一個唯一的ID。Firebase Swift childByAutoId()
好了,但我在這裏使用它是這樣的:
let DeviceInfo = [
"ImageUrl":profileImageUrl!,
"DeviceName":self.DeviceName.text!,
"Description":self.Description.text!,
"Category":self.itemSelected
] as [String : Any]
self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: {(snapShot) in
if snapShot.exists(){
let numberOfDevicesAlreadyInTheDB = snapShot.childrenCount
if numberOfDevicesAlreadyInTheDB < 3{
let newDevice = String("Device\(numberOfDevicesAlreadyInTheDB+1)")
let userDeviceRef = self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid)
userDeviceRef.observeSingleEvent(of: .value, with: {(userDevices) in
if let userDeviceDict = userDevices.value as? NSMutableDictionary{
userDeviceDict.setObject(DeviceInfo,forKey: newDevice as! NSCopying)
userDeviceRef.setValue(userDeviceDict)
}
})
}
else{
let alert = UIAlertController(title: "Sorry", message:"You can only add three devices", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in })
self.present(alert, animated: true){}
}
}else{
self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Device1" : DeviceInfo])
self.ref.child("UserDevices").childByAutoId().setValue([
"ImageUrl":profileImageUrl!,
"DeviceName":self.DeviceName.text!,
"Description":self.Description.text!,
"Category":self.itemSelected,
"name": self.globalUserName,
"email":self.globalEmail ,
"city": self.globalCity,
"phone": self.globalPhone
] as [String : Any])
let alert = UIAlertController(title: "Great", message:"Device has beed added succssfully", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in })
self.present(alert, animated: true){}
}
})
//
} })
}
這是一個按鈕用於將設備添加到火力地堡的一部分。
如果有小於3級的設備,用戶可以添加(其他情況下,這裏),否則,警報應該呈現給用戶「,如果之前情況下,這個別人的(你可以只添加3設備) 。
當我添加第一個設備時,上面的兩個字典已添加到Firebase。但第二次,當我嘗試添加第二個設備時,第一個字典已被添加,但不包含第二個包含childByAutoId
的字典。
這聽起來很奇怪。 childByAutoId
可以給每個註冊用戶一個ID嗎?
我不問如何添加限制! – Mariah
我問爲什麼childByAutoId()第二次添加設備時沒有生成自動ID? – Mariah
任何人,可以給我任何建議嗎?請。 – Mariah