David Sundström David Sundström - 4 months ago 22
iOS Question

App crashing when google name return nil from optional value

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

Answer Source

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