0
func getUser2Info(userName: String) -> String {
    var userid:String = "NA"
    ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
        if let users = snapshot.value as! NSDictionary? {
            for (id, info) in users {
                let userId = id as! String
                let userInfo = info as! NSDictionary
                for (property, info) in userInfo {
                    if (property as! String == "username") {
                        //print(info)
                        //print(userName)
                        if (info as! String == userName) {
                            print("almost there")
                            userid = id as! String
                        } else {
                            userid = "NA"
                        }
                    }
                }
            }
        }

    })
    return userid

}

I'm using swift3 and Firebase to create a messaging app. I need to access the user2 (user who is receiving a message) id in order to add them to the chat based on the way I structured the data. In this function, it returns "NA" for userid every time, but it also prints "almost there" so I know that info == userName is true. It won't reassign (userid = id as! String) at all though. Any ideas?

AL.
  • 36,815
  • 10
  • 142
  • 281
  • 2
    See: http://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function – dan Apr 17 '17 at 18:12
  • I'm not sure I understand that... I'm very new to Swift/Xcode – Bianca Sicich Apr 17 '17 at 18:26
  • 1
    There are a number of issues with this code. Most importantly, the return userid will execute before the code in the closure. Why? Firebase is asynchronous - Firebase data is only valid within the closure and it takes time for data to get from the server to your app. A lot more time than it takes to get to the return userid line. Do not return data involving closures, work with the data within the closure and proceed to the next step from within the closure - guaranteeing your vars are populated. – Jay Apr 17 '17 at 21:28
  • Also see [this answer](http://stackoverflow.com/questions/37104816/finish-asynchronous-task-in-firebase-with-swift/37124220#37124220) – Jay Apr 17 '17 at 21:30
  • and... It's not clear what you are trying to accomplish. Can you clarify what you are trying to do and also provide a sample of your Firebase structure as TEXT please, no images. You can obtain that through the Firebase console -> three dots on right, export JSON. – Jay Apr 17 '17 at 21:33
  • For code readability... `guard` is your friend :-) https://thatthinginswift.com/guard-statement-swift/ – Nicolas Miari Apr 18 '17 at 02:27

0 Answers0