简体   繁体   中英

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?

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()
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM