Saturday, September 13, 2014

iOS Facebook SDK Email 구하기

페이스북 로그인 구현시 Email을 페이스북에서 제공하는 FBLoginView를 사용하지 않고 CustomUI 또는 프로그램으로 자동 로그인을 구현할때는 다음과 같은 방법을 사용한다.

프로그램 기본 소스는 FBLoginCustomUISample을 기반으로 사용한다.
https://github.com/fbsamples/ios-howtos.git

CustomLoginViewController.m
@implementation CustomLoginViewController

- (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:@[@"email"]
                                       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];
     }];
  }
}

AppDelegate.m
// This method will handle ALL the session state changes in the app
- (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];
//      [user objectForKey:@"email"];
      [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
          if (error) {
              //error
          } else {
              NSString *email = [user objectForKey:@"email"];
              NSLog(@"email=%@", email);
//              self.myFirstNameLabel.text = user.first_name;
//              self.myLastNameLabel.text = user.last_name;
              // self.myEmailLabel.text = @"";
          }
      }];
    return;
  }

No comments:

Post a Comment