我使用以下代码登录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) }
这将在webview中启动FB.如果用户从FB帐户接受应用程序,它将按预期返回到应用程序.
但是,如果用户单击否或单击带有FB的webview中的完成按钮,应用程序将崩溃说(致命错误:在解开可选值时意外发现为零)
标记此行:
if(fbloginresult.grantedPermissions.contains("email"))
那么,如果用户点击"否"或"完成",为什么应用程序会崩溃?
首先检查用户是否取消登录.应用程序崩溃,因为没有授予权限.FBSDKLoginManagerLoginResult
if (error == nil){ let fbloginresult : FBSDKLoginManagerLoginResult = result if result.isCancelled { return } if(fbloginresult.grantedPermissions.contains("email")) { self.getFBUserData() } }