0

My app is using Google SDK to collect users names when logged in. This works seamlessly. However, when I press the done button on the google login page I get the error. "Fatal error: unexpectedly found nil when unwrapping an optional value"

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {


nameString = user.profile.name


defaults.set(nameString, forKey: "userName")
defaults.set(user.profile.email, forKey: "email")
defaults.set(user.profile.imageURL(withDimension: 50)!, forKey: "image")

print("email: \(user.profile.email!)")
print("name: \(user.profile.name!)")
print("lastname: \(user.profile.familyName!)")
print("lastname: \(user.profile.imageURL(withDimension: 50))")


self.dismiss(animated: true, completion: nil)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserLoggedIn"), object: nil)

So this is the function which I am using to receive names and saving them via userDeafaults.

The actual problem is the line "nameString = user.profile.name" Because when your press done on the login screen you are skipping to login. Which result in that it will not receive any data from user.profile.name.

How could I solve this problem? so if user.profile.name does not contain anything, it will not save the name to namestring.

Would really appreciate som help. Thank you :)

Dima
  • 23,484
  • 6
  • 56
  • 83

1 Answers1

0

You have to check if the nameString is not nil to safely unwrap it inside an if let statement

if let nameString = user?.profile.name {
    // here your safe to use the nameString it check's if it's not nil
    defaults.set(nameString, forKey: "userName")
} 

or as @vacawama said you can use a guard statement to check if the string is not nil. but with guard statement you have to keep in mind that you have to return. Which means if name is nil it will break out of function.

There is another way as well to check if your string contains characters. how to check for those you can read more here extending Strings extension

how to unwrap it using guard

guard let nameString = nameString else { return }

if you don't want to use guard let or if let then you can directly check if nameString is not empty

guard nameString != nil  else {
        return
}

after this guard check you can force unwrap the nameString because if nameString is nil you will not pass that check

vacawama
  • 150,663
  • 30
  • 266
  • 294
Khalid Afridi
  • 913
  • 5
  • 12
  • Thx:) but, hmm it still givs the same error :/ How would you write the guard block more exactly? – David Sundström May 08 '17 at 20:09
  • you can use guard in different ways I am going to edit my answer where I will add guard as well – Khalid Afridi May 08 '17 at 20:14
  • `if let nameString = user?.profile.name {`. Avoid the force unwrap of the implicitly unwrapped optional `user`. You should probably just change `user` to `GIDGoogleUser?`. – vacawama May 08 '17 at 20:17