如何使用 Facebook SDK 4.6 中的登录 iOS?

How do I use the login in Facebook SDK 4.6 for iOS?

我正在使用此代码登录 FB:

@IBAction func fbloginbtn(sender: AnyObject) {

    FBSDKLoginManager().logInWithReadPermissions(["public_profile", "email","user_location","user_about_me", "user_photos", "user_website"], handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                if((FBSDKAccessToken.currentAccessToken()) != nil){
                    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
                        if (error == nil){
                            //do sth
                        }
                    })
                }
            } 
        }
    })
}

但是 loginwithreadpermissions 在 SDK 4.6 中已弃用

我应该如何更改此代码?

如果您查看文档,您也会看到对备选方案 api 的提及。 从 FBSDKLoginManager 的文档中可以看出:

- (void)logInWithReadPermissions:(NSArray *)permissions
                         handler:(FBSDKLoginManagerRequestTokenHandler)handler
__attribute__((deprecated("use logInWithReadPermissions: fromViewController:handler: instead")));

所以有一种新方法,它也采用附加参数 UIViewController,以确定从何处启动登录序列。正如文档所说:

- (void)logInWithReadPermissions:(NSArray *)permissions
              fromViewController:(UIViewController *)fromViewController
              handler:(FBSDKLoginManagerRequestTokenHandler)handler;

参数的解释是:

fromViewController - The view controller to present from. If nil, the topmost view controller will be automatically determined as best as possible.

因为只有一个附加参数,您可以像这样将其添加到现有实现中:

FBSDKLoginManager().logInWithReadPermissions(["public_profile", "others"],
                           fromViewController:self //<=== new addition, self is the view controller where you're calling this method.
                           handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
})

最新的xcode应该也会在你写的时候给你建议,logInWithReadPermissions所有可用的选项。