UID在firebase中为零

时间:2019-05-25 04:24:36

标签: ios swift firebase

在我的AppDelegate.swift中添加了此代码, 在这里,if user!= nil定义了一个名为UserService的类,

let authListener = Auth.auth().addStateDidChangeListener { (auth, user) in

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        if user != nil {
            UserService.observeUserProfile(user!.uid) { userProfile in
                UserService.currentUserProfile = userProfile
            }
            //

            let controller = storyboard.instantiateViewController(withIdentifier: "Home") as! UINavigationController
            self.window?.rootViewController = controller
            self.window?.makeKeyAndVisible()
        } else {

            UserService.currentUserProfile = nil

            // menu screen
            let controller = storyboard.instantiateViewController(withIdentifier: "SignIn") as! SignInViewController
            self.window?.rootViewController = controller
            self.window?.makeKeyAndVisible() 
        }
    }

在UserService()

class UserService{
     static var currentUserProfile:User?

    static func observeUserProfile(_ uid:String, completion: @escaping ((_ user:User?)->())) {
        let userRef = Database.database().reference().child("users/profile/\(uid)")


        userRef.observe(.value, with: { snapshot in
            var user:User?

            if let dict = snapshot.value as? [String:Any],
                let username = dict["username"] as? String,
                let profileImage = dict["profileImage"] as? String,
                let url = URL(string:profileImage) {

                user = User(uid: snapshot.key, username: username, profileImage: url)
            }

            completion(user)
        })
    }
}

在我的profileViewController.swift中,我需要获取当前用户uid, 但始终返回nil。为什么会这样?

 guard let userProfile = UserService.currentUserProfile else { return
 }

但是我这样添加,我可以得到uid。为什么我无法使用UserService获取uid

  let userid: String = (Auth.auth().currentUser?.uid)!
 print(userid)

输出为: HwXwld5YoDO0YWm6EDvtTRgl7gG3

0 个答案:

没有答案