我有一个在线iOS应用,我需要知道用户名和编号以及在线用户名和编号,因此我使User结构具有一个childByAutoID,可以在创建子名称和子名称时添加它。但是问题是我试图统计在线用户并将其显示在ViewController上,所以我的想法是使Online User json结构在登录时添加,并在注销时删除,因此我将名称+ phone设为“在线用户”结构中名称和数字的父项,但是每次我尝试从注销Viewcontroller访问它时,变量名+数字都返回空,因此如果没有子项ID,我就无法将其从Firebase数据库中删除>
我不想为在线用户使用childByAutoId,因为我不知道如何存储密钥,因为我使用的是异步函数,这也使得如何检索密钥太复杂
//1st view controller
func getID() -> String {
return String(nameField.text! + numberField.text!)
}
@IBAction func linkTapped(_ sender: Any) {
if (nameField.text != nil && numberField.text != nil) {
let alert = UIAlertController(title: "Phone Number", message: "Is this your phone number? \n \(numberField.text!)", preferredStyle: .alert)
let action = UIAlertAction(title: "Yes", style: .default) { (UIAlertAction) in
PhoneAuthProvider.provider().verifyPhoneNumber("+1 " + self.numberField.text!, uiDelegate: nil) {
(verificationID, error) in
if error != nil {
print("error: \(String(describing: error?.localizedDescription))")
print(self.numberField.text ?? "no number entered")
} else {
getID()
let defaults = UserDefaults.standard
defaults.set(verificationID, forKey: "authVID")
defaults.synchronize()
self.performSegue(withIdentifier: "code", sender: Any?.self)
let ref = Database.database().reference().child("Users").childByAutoId()
let values = ["Name": self.nameField.text, "Phone": self.numberField.text]
ref.updateChildValues(values as [AnyHashable : Any], withCompletionBlock: { (err, ref) in
if err != nil {
print(err as Any)
return
}
print("user saved into firebase db")
})
let ref2 = Database.database().reference().child("Online Users")
let onlineRef = ref2.child(self.getID())
onlineRef.updateChildValues(values as [AnyHashable : Any])
}
}
}
let cancel = UIAlertAction(title: "No", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "You left me empty", message: "please fill your name and number", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
}
}
//第二视图控制器
@IBAction func signOutFunction(_ sender: Any) {
do {
try Auth.auth().signOut()
let newVar = ViewController()
let ref = Database.database().reference().child("Online Users")
ref.child(newVar.getID()).removeValue()
self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)
} catch let error {
print("not signed in...", error)
}
}