在Firebase Swift 3中以userID添加数据时出错
我试图通过注册用户在Firebase中的相应userID添加数据,但它给了我错误“ unexpectedly found nil while unwrapping an optional value
”现在我不知道是什么问题。 但是当我在代码中分别使用没有添加userID
代码时,数据被成功添加了。 但是当我添加userID
下面的ref
然后得到错误。
注册
let userID = FIRAuth.auth()?.currentUser?.uid ref.child("user_registration").child(userID!).setValue(["username": self.fullName.text, "email": self.emailTextField.text,"contact": self.numberText.text, "city": self.myCity.text, "state": self.countryText.text, "gender": genderGroup, "blood": bloodGroup])
你需要了解错误。 你是强制解开userID
这不是一个好主意,因为用户可能会或可能不会在您调用此API时login。 以下更改将解决您的问题。
if let userID = FIRAuth.auth()?.currentUser?.uid { ref.child("user_registration").child(userID).setValue(["username": self.fullName.text, "email": self.emailTextField.text,"contact": self.numberText.text, "city": self.myCity.text, "state": self.countryText.text, "gender": genderGroup, "blood": bloodGroup] } else { // ask the user to login in // present your login view controller }
您的用户没有login=>
展开错误。 你需要有这样的东西:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // FireBase init part FIRApp.configure() FIRDatabase.database().persistenceEnabled = false self.storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) // Setting initial viewController for user loggedIn? if(FIRAuth.auth()?.currentUser != nil) { self.window?.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "MainTabBarController") } else { self.window?.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginPage") } return true
}
在你的AppDelegate
。 它会将您的初始视图控制器更改为login页面,如果用户没有login。
有了这个代码,你可以强制展开。
希望能帮助到你