0

I have tried many solutions to make this work, but it doesn't seem to work with me. These are the solutions I have tried:

Firebase Retrieving Data in Swift

https://firebase.google.com/docs/database/ios/read-and-write

https://www.raywenderlich.com/187417/firebase-tutorial-getting-started-3

My database

I am trying to retrieve the deviceToken of the currently logged in user, for example if John logs in, it would assign or retrieve his deviceToken and assign it to a variable.

The closest I have got was with this code, but I get every profile with every data stored in that profile instead of the currently logged in one.

let userID = Auth.auth().currentUser?.uid
let ref = Database.database().reference(withPath: "users/profile/\(userID)")
ref.observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() { 
        return 
    }       

    let token = snapshot.childSnapshot(forPath: "deviceToken").value
    print(token!)

})
pacification
  • 5,838
  • 4
  • 29
  • 51
F.A
  • 297
  • 1
  • 3
  • 13
  • 1
    Since you're getting data for the node one level above of what's desired, are you sure the user is logged in and a uid exists? What do you see when you print the userID? Alternatively, what happens if you try let ref = Database.database().refrerence(withPath: "users/profile").child(userId)? – sgt_lagrange Jul 19 '18 at 13:51
  • Worked perfectly! – F.A Jul 20 '18 at 08:17

1 Answers1

1

There is an example on the documentation, modifying for your case:

let userID = Auth.auth().currentUser?.uid
ref.child("users").child("profile").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let deviceToken = value?["deviceToken"] as? Int ?? ""

// ...
}) { (error) in
print(error.localizedDescription)
}
Do2
  • 1,751
  • 1
  • 16
  • 28
  • I get an error that says "Argument passed to call that takes no arguments" for the let user = User(deviceToken: deviceToken) part. – F.A Jul 20 '18 at 08:09
  • Turns out I can just comment it out and ignore that line. Thanks! – F.A Jul 20 '18 at 08:18
  • 1
    Yes, in your case it is not needed. I have deleted that line. – Do2 Jul 20 '18 at 08:49