使用自定义登录按钮检索Facebook页面

问题描述 投票:1回答:2

我已经下载了这个用于Facebook自定义登录的示例项目:

FBLoginCustomUISample

作为一个测试,我想在facebook sdk上实现这个方法来检索用户页面,如:

/* make the API call */
[FBRequestConnection startWithGraphPath:@"/me/likes"
                             parameters:nil
                             HTTPMethod:@"GET"
                      completionHandler:^(
                          FBRequestConnection *connection,
                          id result,
                          NSError *error
                      ) {
                          NSLog(@"%@",result);
                      }];

我在CustomLoginViewController.m中将其复制粘贴,如下所示:

- (IBAction)buttonTouched:(id)sender
{
  // If the session state is any of the two "open" states when the button is clicked
  if (FBSession.activeSession.state == FBSessionStateOpen
      || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {

    // Close the session and remove the access token from the cache
    // The session state handler (in the app delegate) will be called automatically
    [FBSession.activeSession closeAndClearTokenInformation];

  // If the session state is not any of the two "open" states when the button is clicked
  } else {
    // Open a session showing the user the login UI
    // You must ALWAYS ask for public_profile permissions when opening a session
    [FBSession openActiveSessionWithReadPermissions:@[@"public_profile"]
                                       allowLoginUI:YES
                                  completionHandler:
     ^(FBSession *session, FBSessionState state, NSError *error) {

       // Retrieve the app delegate
       AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
       // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
       [appDelegate sessionStateChanged:session state:state error:error];
         [FBRequestConnection startWithGraphPath:@"/me/likes?limit=10"
                                      parameters:nil
                                      HTTPMethod:@"GET"
                               completionHandler:^(
                                                   FBRequestConnection *connection,
                                                   id result,
                                                   NSError *error
                                                   ) {
                                   NSLog(@"%@",result);
                               }];
     }];
  }

}

当我登录时,我得到一个空数据。

在facebook工作提供的示例中创建方法后,我尝试在我的SignUpSetProfileDetailsViewController.m类中实现下一个代码:

- (void)facebookButtonFunction{


        // Open a session showing the user the login UI
        // You must ALWAYS ask for public_profile permissions when opening a session
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"public_profile",
                                @"user_interests ",
                                nil];
        [FBSession openActiveSessionWithReadPermissions:permissions
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {

             [FBRequestConnection startWithGraphPath:@"/me/interests"
                                          parameters:nil
                                          HTTPMethod:@"GET"
                                   completionHandler:^(
                                                       FBRequestConnection *connection,
                                                       id result,
                                                       NSError *error
                                                       ) {
                                       NSLog(@"%@",result);
                                   }];
             // Retrieve the app delegate

             // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
             [self sessionStateChanged:session state:state error:error];
         }];
    }

- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
    // If the session was opened successfully
    if (!error && state == FBSessionStateOpen){
        NSLog(@"Session opened");
        // Show the user the logged-in UI
        [self userLoggedIn];
        return;
    }
    if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
        // If the session is closed
        NSLog(@"Session closed");
        // Show the user the logged-out UI
        [self userLoggedOut];
    }

    // Handle errors
    if (error){
        NSLog(@"Error");
        NSString *alertText;
        NSString *alertTitle;
        // If the error requires people using an app to make an action outside of the app in order to recover
        if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
            alertTitle = @"Something went wrong";
            alertText = [FBErrorUtility userMessageForError:error];
            [self showMessage:alertText withTitle:alertTitle];
        } else {

            // If the user cancelled login, do nothing
            if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
                NSLog(@"User cancelled login");

                // Handle session closures that happen outside of the app
            } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession){
                alertTitle = @"Session Error";
                alertText = @"Your current session is no longer valid. Please log in again.";
                [self showMessage:alertText withTitle:alertTitle];

                // For simplicity, here we just show a generic message for all other errors
                // You can learn how to handle other errors using our guide: https://developers.facebook.com/docs/ios/errors
            } else {
                //Get more error information from the error
                NSDictionary *errorInformation = [[[error.userInfo objectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:@"body"] objectForKey:@"error"];

                // Show the user an error message
                alertTitle = @"Something went wrong";
                alertText = [NSString stringWithFormat:@"Please retry. \n\n If the problem persists contact us and mention this error code: %@", [errorInformation objectForKey:@"message"]];
                [self showMessage:alertText withTitle:alertTitle];
            }
        }
        // Clear this token
        [FBSession.activeSession closeAndClearTokenInformation];
        // Show the user the logged-out UI
        [self userLoggedOut];
    }
}
- (void)userLoggedOut
{
    // Set the button title as "Log in with Facebook"
    [facebookButtonLabel setText:@"Connect"];
    [facebookButtonLabel setTextColor:[UIColor whiteColor]];
}

// Show the user the logged-in UI
- (void)userLoggedIn
{
    // Set the button title as "Log out"
    [facebookButtonLabel setText:@"Connected"];
    [facebookButtonLabel setTextColor:[UIColor yellowColor]];

    // Welcome message
    [self showMessage:@"You're now logged in with Facebook!" withTitle:@"Welcome!"];

}

- (void)showMessage:(NSString *)text withTitle:(NSString *)title
{
    [[[UIAlertView alloc] initWithTitle:title
                                message:text
                               delegate:self
                      cancelButtonTitle:@"OK!"
                      otherButtonTitles:nil] show];
}

以编程方式添加按钮的地方,我所做的就是丢失appdelegate实现

ios xcode facebook
2个回答
1
投票

将user_likes添加到权限

 NSArray *permissions = [[NSArray alloc] initWithObjects:
                                  @"public_profile",
                                  @"user_likes",
                                  nil];

虽然单独管理权限列表会更好,但由于存在大量权限(读取和写入),因此需要管理以获取各种数据


0
投票

更新了按钮功能,现在它可以工作:

- (IBAction)buttonTouched:(id)sender
{
  // If the session state is any of the two "open" states when the button is clicked
  if (FBSession.activeSession.state == FBSessionStateOpen
      || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {

    // Close the session and remove the access token from the cache
    // The session state handler (in the app delegate) will be called automatically
    [FBSession.activeSession closeAndClearTokenInformation];

  // If the session state is not any of the two "open" states when the button is clicked
  } else {
    // Open a session showing the user the login UI
    // You must ALWAYS ask for public_profile permissions when opening a session
      NSArray *permissions = [[NSArray alloc] initWithObjects:
                              @"public_profile",
                              @"user_likes",
                              nil];
    [FBSession openActiveSessionWithReadPermissions:permissions
                                       allowLoginUI:YES
                                  completionHandler:
     ^(FBSession *session, FBSessionState state, NSError *error) {
         /* make the API call */
         [FBRequestConnection startWithGraphPath:@"/me/likes"
                                      parameters:nil
                                      HTTPMethod:@"GET"
                               completionHandler:^(
                                                   FBRequestConnection *connection,
                                                   id result,
                                                   NSError *error
                                                   ) {
                                   NSLog(@"%@",result);
                               }];
       // Retrieve the app delegate
       AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
       // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
       [appDelegate sessionStateChanged:session state:state error:error];
     }];
  }
}

另外我学到的是,在开发者Facebook帐户中,你想要检索user_likes,user_interests和其他类似Facebook图形api请求的应用程序,你需要通过转到Facebook上的状态和评论并提交新评论来将其添加到用户权限关于许可,你需要什么以及如何被起诉。

© www.soinside.com 2019 - 2024. All rights reserved.