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