在加载用户的函数中,我可以检索一个值。但是,当我想将其分配给函数外部的变量时,它什么也没有,如登录功能所示。
加载用户功能
func loadUser(userid: String) -> User {
//print(userid)
let userid = "56ldZFJiv0dpfaABzo78"
var user = User()
let docRef = db.collection("users").document(userid)
docRef.getDocument { (document, error) in
if let document = document {
let first = document.data()!["first"] as! String
let last = document.data()!["last"] as! String
let position = document.data()!["position"] as! String
let company = document.data()!["company"] as! String
let email = document.data()!["email"] as! String
let address = document.data()!["address"] as! String
let userID = document.data()!["userID"] as! String
//Initalize user
user = User(userID: userID,
firstName: first,
lastName: last,
company: company,
address: address,
position: position,
email: email)
print(user.position)
} else {
print("Document does not exist")
}
}
return user
}
登录功能
//MARK: LOGIN
func login() {
Auth.auth().signIn(withEmail: emailField.text!, password: passwordField.text!) { (user, error) in
if error == nil{
//self.performSegue(withIdentifier: "loginToAdmin", sender: self)
//Load user
let loggedOnUser = self.loadUser(userid: Auth.auth().currentUser!.uid)
print(loggedOnUser.userID)
// let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let chatViewController = storyBoard.instantiateViewController(withIdentifier: "chatVC") as! UINavigationController
// self.present(chatViewController, animated: true, completion: nil)
}
else {
DispatchQueue.main.async{
//Display Alert Message if login failed
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
对于第一个函数,我得到一个位置值,如print语句中所述。 对于第二个功能,我的变量“ loggedOnUser”为空。
答案 0 :(得分:0)
您需要完成,因为loadUser
是异步的
func loadUser(userid: String,completion:@escaping(User?) ->()) {
//print(userid)
let userid = "56ldZFJiv0dpfaABzo78"
var user = User()
let docRef = db.collection("users").document(userid)
docRef.getDocument { (document, error) in
if let document = document {
let first = document.data()!["first"] as! String
let last = document.data()!["last"] as! String
let position = document.data()!["position"] as! String
let company = document.data()!["company"] as! String
let email = document.data()!["email"] as! String
let address = document.data()!["address"] as! String
let userID = document.data()!["userID"] as! String
//Initalize user
user = User(userID: userID,
firstName: first,
lastName: last,
company: company,
address: address,
position: position,
email: email)
print(user.position)
completion(user)
} else {
print("Document does not exist")
completion(nil)
}
}
}
致电
self.loadUser(userid: Auth.auth().currentUser!.uid) { res in
if let user = res {
print(user)
}
}