我创建了一个应用程序,当用户注册时,应在该应用程序的Firestore服务器中的用户文档中创建两个值,分别是级别和主题(意味着该值位于/ users / userid中)。
我尝试过手动创建“用户”集合,但是在用户注册后却什么也没创建。
以下是我的代码(SignUpViewController):
import Firebase
var reference: DocumentReference!
func firebaseAuth() {
let userDisplayName = textfieldDisplayName.text!
let userEmail = textfieldEmail.text!
let userPassword = textfieldPassword.text!
if userEmail == "" || userPassword == "" {
labelMessage.isHidden = false
labelMessage.textColor = UIColor.red
labelMessage.text = "Error: A compulsory field is left blank."
} else {
Auth.auth().createUser(withEmail: userEmail, password: userPassword) { (user, error) in
if user != nil && error == nil {
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = userDisplayName
changeRequest?.commitChanges(completion: { (error) in
if error == nil {
let userID = Auth.auth().currentUser?.uid
let dataToSave: [String: Any] = ["level":0, "subjects":[""]]
self.reference = Firestore.firestore().collection("users").document(userID ?? "")
self.reference.setData(dataToSave, completion: { (error) in
if error == nil {
self.performSegue(withIdentifier: "presentInitial", sender: self)
} else {
self.labelMessage.isHidden = false
self.labelMessage.textColor = UIColor.red
self.labelMessage.text = "Error: \(error?.localizedDescription ?? "")"
}
})
self.performSegue(withIdentifier: "presentInitial", sender: self)
} else {
self.labelMessage.isHidden = false
self.labelMessage.textColor = UIColor.red
self.labelMessage.text = "Error: \(error?.localizedDescription ?? "")"
}
})
} else {
self.labelMessage.isHidden = false
self.labelMessage.textColor = UIColor.red
self.labelMessage.text = "Error: \(error?.localizedDescription ?? "")"
}
}
}
}
以下代码来自SignViewViewController重定向到(HomeViewController)的另一个View Controller:
import Firebase
var reference: DocumentReference!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let userID = Auth.auth().currentUser?.uid
reference.getDocument { (docSnapshot, error) in // Fatal error occured here
let data = docSnapshot?.data()
let userLevel = data?["level"] as? String ?? ""
if userLevel == "" {
self.performSegue(withIdentifier: "performSetup", sender: self)
}
}
}
我希望当重定向到首页(通过presentInitial设置)时,首页将读取'level'的值。但是,应用程序崩溃并出现致命错误:“致命错误:意外地发现了nil,同时隐式展开了一个Optional值”,其中“ level”是要从服务器读取的。
答案 0 :(得分:1)
我认为问题不在于Firestore。根据错误消息,代码包装了一个可选值,但是由于它是nil
而失败,因此问题可能出在以下三行:
let userDisplayName = textfieldDisplayName.text!
let userEmail = textfieldEmail.text!
let userPassword = textfieldPassword.text!
有时,当UITextField
没有文本时,其text
是nil
而不是""
,这可能会引起问题。您可以将以下三行替换为:
let userDisplayName = textfieldDisplayName.text ?? ""
let userEmail = textfieldEmail.text ?? ""
let userPassword = textfieldPassword.text ?? ""
这样,当没有文本时,这三个变量将始终为""
,并且检查空白字段的逻辑仍然有效。
编辑:供将来参考,真正的问题不在问题中,而在此答案的注释中。
答案 1 :(得分:0)