在我的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