0

I'm making an Instagram clone, and am wanting to get the username for the user to display. The info is in the Database section of firebase, and I'm trying to do it via a snapshot, but it always returns .

fileprivate func fetchUser() {
    guard let uid = Auth.auth().currentUser?.uid else { return }


    Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value ?? "")
    }) { (err) in
        print("Failed to fetch user:", err)
    }
}

The code format is spaced weird, but thats the code. Am I not getting the Childs right, or what's going on?

EDIT: also here is a snapshot of Firebase Db.Firebase screenshot

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • You have some of the users directly under the root, and others under `/users`. Your code will only be able to read the one under `/users`. The solution is to fix the code that *writes* this user data, to write it at a consistent place. – Frank van Puffelen Jun 02 '18 at 15:18
  • so Frank, even though I have a user under /users, it’s still displaying null. would rewriting the code to put all the users under /users fix it, or no? this is one of my first times using firebase, so i’m quite noobish haha – Mason Bose Jun 02 '18 at 15:45
  • Your data structure is not consistent, which makes it very hard to trust anything (since we don't know which UID your user has). See if you can reproduce it with a hard-coded value for `uid`, and if so update the code in your question. That makes it easier to see what it actually happening. – Frank van Puffelen Jun 02 '18 at 16:13
  • The code in your question works for the posted structure (assuming you are looking for a valid uid within the /users node) so it's unclear what the issue is. In the future, please include your Firebase strucuture as TEXT please, not a link or image. Links break that that would invalidate the question. – Jay Jun 06 '18 at 16:14

1 Answers1

2

Try this:

guard let uid = Auth.auth().currentUser?.uid else { return }
let reference = Database.database().reference()
reference.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in

    guard let dictionary = snapshot.value as? [String: Any] else { return }

    let username = dictionary["username"] as? String

    print(username ?? "")

}, withCancel: nil)
Daniel Dramond
  • 1,538
  • 2
  • 15
  • 26
  • InstagramClone[71556:9641272] TIC Read Status [1:0x0]: 1:57 - Your solution returns this error. (https://stackoverflow.com/questions/46352735/what-is-tic-read-status-157-in-ios11-xcode-9) this is what I found on it – Mason Bose Jun 02 '18 at 16:12
  • @MasonBose Have your added the correct lines for configuring Firebase in your AppDelegate, added in the correct .plist file and authenticated the user? – Daniel Dramond Jun 02 '18 at 17:07
  • @MasonBose This answer works correctly - tested in my own project and does not return any errors. – Jay Jun 06 '18 at 16:12