简体   繁体   English

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

[英]Facebook SDK Objective-C trigger event after login

I'm new to IOS Application Development and this is the first time I've integrated the Facebook SDK into an application. 我是IOS应用程序开发的新手,这是我第一次将Facebook SDK集成到应用程序中。 I'm using my initial view controller to authenticate the user via the Facebook SDK and redirect him to another view controller once he is authenticated. 我正在使用我的初始视图控制器通过Facebook SDK对用户进行身份验证,并在经过身份验证后将其重定向到另一个视图控制器。 Additionally, once he clicks on log out, I want to be able to redirect the user back to this initial view controller. 此外,一旦他点击退出,我希望能够将用户重定向回这个初始视图控制器。

I'm using the following code (inside the viewDidLoad function) to add the Facebook login button to my view: 我正在使用以下代码(在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];

The button is working fine, but I noticed that right after I login, the [FBSDKAccessToken currentAccessToken] is nil in all the view controller lifecycle functions. 按钮工作正常,但我注意到,在我登录后, [FBSDKAccessToken currentAccessToken]在所有视图控制器生命周期功能中都是nil Basically, it seems that this value is initialised by the Facebook SDK after my page is loaded. 基本上,似乎这个值是在我的页面加载后由Facebook SDK初始化的。

Is there any way to execute a function right after this access token gets initialised, so that I can successfully redirect to a different controller? 有没有办法在这个访问令牌初始化后立即执行一个函数,这样我就可以成功重定向到另一个控制器? or is there any functionality that might help me achieve this behaviour? 或者是否有任何功能可以帮助我实现这种行为? Similarly, i'd like to be able to redirect the user back to this initial view controller once he clicks the logout button from a different view. 同样,我希望能够在用户从其他视图单击注销按钮后将用户重定向回该初始视图控制器。

I found that, by far, the easiest solution to this problem would be setting View Controller as a delegate for the login button and implementing the following functions: 我发现,到目前为止,解决此问题的最简单方法是将View Controller设置为登录按钮的委托并实现以下功能:

First, you have to use this protocol: 首先,您必须使用此协议:

@interface LoginController ()<FBSDKLoginButtonDelegate>

Then, set the view Controller as the button's delegate 然后,将视图Controller设置为按钮的委托

loginButton.delegate = self;

Finally, you would have to make sure that the following 2 methods are implemented 最后,您必须确保实现以下两种方法

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

I think you have to use FBGraphApi which will give you call back when user will login successfully. 我想你必须使用FBGraphApi,当用户登录成功时,它会给你回电。

try code below: 试试下面的代码:

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

}

By calling above function you will get call back in ComplitionBlock. 通过调用上面的函数,您将在ComplitionBlock中回调。

Here is the full and complete code to fetch user's information. 以下是获取用户信息的完整代码。

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);
                  }
              }];
         }
     }
 }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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