我正在创建我的第一个应用程序(并且是 swift 的新手)。当我从 Facebook 登录时,姓名和电子邮件会保存在 Firestore 中。我试图将 facebook 中的名称设置为变量以在其他地方使用它,但我无法分配该值,总是在控制台中显示“nil”。有人可以帮我吗?
- 我设置了变量
var userN: String?
- 我从 Firestore 获取数据
func readDatabase(){
let db = Firestore.firestore()
let docRef = db.collection("users").document("email")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
let data = document.data()
let userName = data!["name"]! as! String
print(userName)
let userEmail = data!["email"]! as! String
print(userEmail)
let containerController = ContainerController()
let containerController.userN = userName;
return
}
}
}
我想分配userN = userName
,以在其他 View 中使用它
我怎样才能做到这一点?谢谢
最佳答案
如果您使用 StoryBoards,您可以通过 segue 函数传递它;
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourStoryBoardSegue" {
if let viewController = segue.destination as? ContainerController {
viewController.userN = userName
}
}
}
否则,最佳实践是使用委托(delegate)方法。
搜索堆栈溢出以获取使用委托(delegate)传递数据的最佳实践。
关于swift - 从 firestore 分配用户名值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919056/