Facebook SDK Objective-C 登录后触发事件

Facebook SDK Objective-C trigger event after login

我是 IOS 应用程序开发的新手,这是我第一次将 Facebook SDK 集成到应用程序中。 我正在使用我的初始视图控制器通过 Facebook SDK 对用户进行身份验证,并在他通过身份验证后将他重定向到另一个视图控制器。此外,一旦他点击注销,我希望能够将用户重定向回这个初始视图控制器。

我正在使用以下代码(在 viewDidLoad 函数内)将 Facebook 登录按钮添加到我的视图中:

FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];

// setting the facebook button position
float screenHeight = [[UIScreen mainScreen] bounds].size.height;
float screenWidth = [[UIScreen mainScreen] bounds].size.width;
CGPoint origin = CGPointMake(screenWidth/2, screenHeight - 100);

// Optional: Place the button in the center of your view.
loginButton.center = origin;
[self.view addSubview:loginButton];

按钮工作正常,但我注意到在我登录后,所有视图控制器生命周期函数中的 [FBSDKAccessToken currentAccessToken]nil。基本上,这个值似乎是在我的页面加载后由 Facebook SDK 初始化的。

有什么方法可以在这个访问令牌初始化后立即执行一个函数,以便我可以成功重定向到另一个控制器?或者是否有任何功能可以帮助我实现这种行为? 同样,我希望能够在用户从不同视图单击注销按钮后将用户重定向回此初始视图控制器。

我认为您必须使用 FBGraphApi,它会在用户成功登录时给您回电。

尝试下面的代码:

-(void)FBLoginWithViewController:(UIViewController *)viewController withCompletion:(FBDataBlock)block
{
    [login logInWithReadPermissions: @[@"public_profile"]
             fromViewController:viewController
             handler:^(FBSDKLoginManagerLoginResult *permissionResult, NSError *error) {
                 if (error) {

                     block(permissionResult,error,nil);

                 } else if (permissionResult.isCancelled) {

                     block(permissionResult,error,nil);

                 } else {

                     [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{ @"fields" : @"id,name,picture,email,friends"}]
                      startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id response, NSError *error) {

                              block(permissionResult,error,response);
                      }];
                 }
             }];

}

通过调用上述函数,您将在 ComplitionBlock 中获得回调。

这是获取用户信息的完整代码。

FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
 logInWithReadPermissions: @[@"public_profile",  @"user_friends", @"email"]
 fromViewController:self
 handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
     if (error) {
         DLog(@"Process error======%@",error.description);
         indicators.hidden=YES;
         [indicators stopAnimating];
     } else if (result.isCancelled) {
         DLog(@"Cancelled");
         indicators.hidden=YES;
         [indicators stopAnimating];
     } else {

         if ([FBSDKAccessToken currentAccessToken]) {



             [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, link, first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , gender ,friendlists"}]
              startWithCompletionHandler:^(
                                           FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                  if (!error)
                  {

                      //  NSLog(@"fetched user:%@", result);

                      // [self fetchingFacebookFriends];

                      [defFacebookData setObject:[result objectForKey:@"email"] forKey:@"fbEmail"];

                      [defFacebookData setObject:[result objectForKey:@"id"] forKey:@"fbID"];


                      //PASS ID
                      getFbid  = [result objectForKey:@"id"];
    NSLog(@"getFbid========>%@",getFbid);

                      //PASS FIRST NAME
                      getFbFirstName=[result objectForKey:@"first_name"];

    NSLog(@"first======>%@",getFbFirstName);

                      //PASS LAST NAME
                      getFBlastName=[result objectForKey:@"last_name"];
    NSLog(@"first======>%@",getFBlastName);

                      //PASS EMAIL
                      getFbemail=[result objectForKey:@"email"];
    NSLog(@"first======>%@",getFbemail);

                      //PASS PHONE
                      getfbGender=[result objectForKey:@"gender"];
    NSLog(@"first======>%@",getfbGender);


                      [defFacebookData setObject:[result objectForKey:@"name"] forKey:@"fbName"];

                      // Image
                      FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                                    initWithGraphPath:[NSString stringWithFormat:@"me/picture?type=large&redirect=false"]
                                                    parameters:nil
                                                    HTTPMethod:@"GET"];
                      [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                                            id fbImageResult,
                                                            NSError *error) {

NSString *strURL = [NSString stringWithFormat:@"%@",[[fbImageResult objectForKey:@"data"] objectForKey:@"url"]];

    NSLog(@"strURL=====>%@",strURL);

[defFacebookData setObject:strURL forKey:@"fbImage"];

                          [defFacebookData synchronize];


                          NSDictionary *fbdict=[NSDictionary dictionaryWithObjectsAndKeys:getFbid,@"id",getFbFirstName,@"first_name",getFBlastName,@"last_name",getFbemail,@"email",getfbGender,@"gender",strURL,@"fbImage", nil];

                          NSLog(@"done=========>%@",fbdict);

     UIStoryboard*storyboard=[AppDelegate storyBoardType];

    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];


    BOOL fblogin =[defaults boolForKey:@"KeyEditProfile"];

        if (fblogin)
            {

                UIStoryboard*Storyboard=[AppDelegate storyBoardType];
                DashboardVC* tabbarController = (DashboardVC*)[Storyboard instantiateViewControllerWithIdentifier:@"DashboardVCId"];



                indicators.hidden=YES;
                [indicators stopAnimating];

                [self.navigationController pushViewController:tabbarController animated:YES];

        }

    else
    {
    EditFBVC *cpvc=(EditFBVC*)[storyboard instantiateViewControllerWithIdentifier:@"EditFBVCId"];
    NSLog(@"get fb id  ===%@",getFbid);


    cpvc.dictFacebookdict =fbdict;

    cpvc.strFBlogin =@"fbAllDataValue";

        indicators.hidden=YES;
        [indicators stopAnimating];

    [self.navigationController pushViewController:cpvc animated:YES];

    }
                      }];
                  }
                  else{

                      DLog(@"error is %@", error.description);
                  }
              }];
         }
     }
 }];

我发现,到目前为止,解决此问题的最简单方法是将 View Controller 设置为登录按钮的委托并实现以下功能:

首先,你必须使用这个协议:

@interface LoginController ()<FBSDKLoginButtonDelegate>

然后,将视图控制器设置为按钮的委托

loginButton.delegate = self;

最后,您必须确保实现以下 2 个方法

- (void)  loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                error:(NSError *)error{
   //use your custom code here
  //redirect after successful login 
}
- (void) loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{
  //use your custom code here
  //redirect after successful logout 
}