Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift ios facebook login crashes app if user cancel login

I am using the following code to login with facebook:

@IBAction func fbLoginBtnDidTouch(sender: AnyObject) {
        let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
        fbLoginManager.logInWithReadPermissions(["email"], fromViewController: self) { (result, error) -> Void in
            if (error == nil){
                let fbloginresult : FBSDKLoginManagerLoginResult = result
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    self.getFBUserData()
                }
            }
        }
    }

AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
    }

This will launch FB in a webview. If the user accept the app from the FB account it will return to the app as expected.

But if the user clicks on NO or clicks the Done button in the webview with FB the app will crash saying (fatal error: unexpectedly found nil while unwrapping an Optional value)

Marking this line:

if(fbloginresult.grantedPermissions.contains("email"))

So why does the app crash if the user clicks on No or Done?

like image 738
user2722667 Avatar asked Apr 03 '16 20:04

user2722667


1 Answers

First check if user canceled login. App crashed because there are no granted permissions. FBSDKLoginManagerLoginResult

if (error == nil){
   let fbloginresult : FBSDKLoginManagerLoginResult = result
   if result.isCancelled {
      return
   }
   if(fbloginresult.grantedPermissions.contains("email"))
     {
         self.getFBUserData()
     }
}
like image 165
tbilopavlovic Avatar answered Sep 20 '22 23:09

tbilopavlovic