Error while adding data in userID in Firebase Swift 3

不问归期 提交于 2019-12-25 16:46:13

问题


I am trying to add data by respective userIDs in Firebase by sign up the user, but it gives me error "unexpectedly found nil while unwrapping an optional value" now I don't know what the matter is. But when I use code without adding userID in ref respectively the data is added successfully. but when I add userID following ref then got error.


SignUp

  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])


回答1:


You need to understand the error. You are force unwrapping the userID which is not a good idea because the user may or may not be logged in when you calling this API. Below changes will resolve your issue.

 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
 }



回答2:


Your user is not logged in => error in unwrapping. You need to have something like:

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

}

in your AppDelegate. It will change your initial view controller to login page, If user is not logged in.

With this code you can force unwrapping.

Hope it helps



来源:https://stackoverflow.com/questions/44129482/error-while-adding-data-in-userid-in-firebase-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!