我刚开始使用Swift / firebase,对不起,我很抱歉。我正在使用childbyautoid将数据写入Firebase数据库。我想访问另一个类中的最后一个键/ ID。
let postName = Database.database().reference().child("Event").childByAutoId()
let postNameObject = [
"EventName": NameTextField.text,
"timestamp": [".sv":"timestamp"],
"userID": Auth.auth().currentUser!.uid
] as [String:Any]
postName.setValue(postNameObject, withCompletionBlock: { error, ref in
if error == nil {
self.dismiss(animated: true, completion: nil)
} else {
}
})
let childautoID = postName.key
我希望能够在另一个类中调用childautoID,我们找到了另一种更新此节点的方法。
答案 0 :(得分:0)
您也许可以创建一个用于管理Firebase方法的单例类。每当使用Firebase构建应用程序时,我都会做类似的事情。这样,您可以跨多个类引用值并全局使用与Firebase相关的方法。在采用这种方法之前,我发现自己重写了用于将对象上传到Firebase的相同代码。单例可让您创建可重用的代码,包括存储此全局类中设置的“最后一个键”。
class FirebaseManager {
//You've probably seen something similar to this "shared" in other Apple frameworks
//Maybe URLSession.shared or FileManager.default or UserDefaults.standard or SKPaymentQueue.default() or UIApplication.shared
static var shared = FirebaseManager()
func createEvent(name: String, timeStamp: [String:String], uid: String) {
let postNameObject = [
"EventName": name,
"timestamp": timeStamp,
"userID": uid
] as [String:Any]
postName.setValue(postNameObject, withCompletionBlock: { error, ref in
if error == nil {
self.dismiss(animated: true, completion: nil)
} else {
//Do something
}
})
let childautoID = postName.key
//Whatever else you need to do in the function below here...
}
}
用法:
class SomeViewController: UIViewController {
@IBOutlet var nameTextField: UITextField!
//Some code...
@IBAction func createEventButtonPressed(_ sender: Any) {
FirebaseManager.shared.createEvent(name: nameTextField.text, timeStamp: [".sv":"timestamp"], uid: Auth.auth().currentUser!.uid)
}
//Some more code...
}
类似地,您可以在我们的lastKey
类中添加一个类型为String
的名为FirebaseManager
的值。请注意,我们添加到FirebaseManager
类顶部的变量:
class FirebaseManager {
var lastKey: String!
static var shared = FirebaseManager()
func createEvent(name: String, timeStamp: [String:String], uid: String) {
let postNameObject = [
"EventName": name,
"timestamp": timeStamp,
"userID": uid
] as [String:Any]
postName.setValue(postNameObject, withCompletionBlock: { error, ref in
if error == nil {
self.dismiss(animated: true, completion: nil)
} else {
//Do something
}
})
let childautoID = postName.key
//Whatever else you need to do in the function below here...
}
}
类似地,我们可以在一个视图控制器中设置该值:
class ViewControllerA: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
FirebaseManager.shared.lastKey = "aBcDeFg9876543210"
}
}
并在另一个加载前一个视图控制器的视图控制器中获取此值:
class ViewControllerB: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(FirebaseManager.shared.lastKey)
}
}
打印:aBcDeFg9876543210
这是static
关键字的美。您可以在此处了解有关创建单例类的更多信息:https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift