1

I just started to use Swift/firebase, sorry for my noobiness. I am writing data into firebase database using childbyautoid. I want to access the last key/id in another class.

    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

I want to be able to call childautoID in another class our find another way to update this node.

timbre timbre
  • 12,648
  • 10
  • 46
  • 77

1 Answers1

0

You could maybe make a singleton class for managing Firebase methods. I do something similar whenever building apps with Firebase. This lets you reference values and use methods related to Firebase globally, across multiple classes. Before I adopted this method, I found myself rewriting the same code for uploading objects to firebase. A singleton will let you create reusable code, including storage of a "last key" set in this global class.

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...

    }

}

Usage:

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...
}

Similarly, you could add a value called lastKey of type String in our FirebaseManager class. Note the variable we add to the top of our FirebaseManager class:

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...

    }

}

Similarly, we can set this value in one view controller:

class ViewControllerA: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        FirebaseManager.shared.lastKey = "aBcDeFg9876543210"
    }
}

And grab this value in another view controller that loads following the previous view controller:

class ViewControllerB: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print(FirebaseManager.shared.lastKey)
    }
}

Prints: aBcDeFg9876543210

This is the beauty of the static keyword. You can learn more about creating singleton classes here: https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift

David Chopin
  • 2,780
  • 2
  • 19
  • 40