Error while adding data in userID in Firebase Swif

2019-08-17 14:56发布

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

enter image description here

2条回答
Anthone
2楼-- · 2019-08-17 15:15

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

查看更多
戒情不戒烟
3楼-- · 2019-08-17 15:22

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
 }
查看更多
登录 后发表回答