2013-05-25 3 views
12

저는 iPhone 개발을 처음 사용합니다. 나는 사용자가 페이스 북을 통해 2 번의 로그인을하는 App을하고있다. 일단 자신의 자격 증명을 제출하고 Sign In 버튼을 클릭하면 Facebook에서 이름, 이메일 및 성별과 같은 세부 정보를 가져와야하며 사용자를 가져온 후에는 사용자를 감독해야한다. 채워진 세부 정보가있는 앱의 등록 페이지로 이동하려면이 앱이 iPhone 4, 5 및 5 용으로 호환되어야합니다.iOS에서 Facebook의 사용자 세부 정보를 가져 오는 중

Facebook Graph API를 사용하여이 작업을 시도했지만 가져올 수 없으므로 누구나 할 수 있습니다. 도와주세요.

미리 감사드립니다.

+3

안녕하세요. 당신은 당신이 시도한 것을 올릴 필요가 있습니다. 우리는 당신을 돕기 위해 노력할 것입니다, 그러나 당신이 적어도 그것에 노력을 기울 였음을 보여준 후에 요. –

답변

1
1

.... 그 것이다 당신을 도움이되기를 바랍니다 그래프 경로를 사용하여 사용자 정보를 얻는 방법.

[FBSession openActiveSessionWithReadPermissions:@[@"email",@"user_location",@"user_birthday",@"user_hometown"] 
            allowLoginUI:YES 
           completionHandler:^(FBSession *session, FBSessionState state, NSError *error) { 

            switch (state) { 
             case FBSessionStateOpen: 
              [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) { 
               if (error) { 
               NSLog(@"error:%@",error);            
               } 
               else 
               {             
                // retrive user's details at here as shown below 
                NSLog(@"FB user first name:%@",user.first_name); 
                NSLog(@"FB user last name:%@",user.last_name); 
                NSLog(@"FB user birthday:%@",user.birthday); 
                NSLog(@"FB user location:%@",user.location); 
                NSLog(@"FB user username:%@",user.username); 
                NSLog(@"FB user gender:%@",[user objectForKey:@"gender"]); 
                NSLog(@"email id:%@",[user objectForKey:@"email"]); 
                NSLog(@"location:%@", [NSString stringWithFormat:@"Location: %@\n\n", 
                     user.location[@"name"]]); 

               } 
              }]; 
              break; 

             case FBSessionStateClosed: 
             case FBSessionStateClosedLoginFailed: 
              [FBSession.activeSession closeAndClearTokenInformation]; 
              break; 

             default: 
              break; 
            } 

           } ]; 

및 코드에서 FacebookSDK/FacebookSDK.h을 가져 깜빡하지 않습니다

-(void)getEmailId 
{ 
[facebook requestWithGraphPath:@"me" andDelegate:self]; 
} 

- (void)openSession 
{ 
if (internetActive) { 
    NSArray *permissions=[NSArray arrayWithObjects:@"read_stream",@"email",nil]; 

    [FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler: 
    ^(FBSession *session, 
    FBSessionState state, NSError *error) { 
    [self sessionStateChanged:session state:state error:error]; 
    }]; 
}else 
{ 
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"Internet Not Connected" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
    [alert show]; 
} 
} 

#pragma mark- request delegate methods 

- (void)request:(FBRequest *)request didLoad:(id)result 
{ 
    NSLog(@"request did load successfully...."); 

// __block NSDictionary *dictionary=[[NSDictionary alloc] init]; 

if ([result isKindOfClass:[NSDictionary class]]) { 
    NSDictionary* json = result; 

    NSLog(@"email id is %@",[json valueForKey:@"email"]); 
    NSLog(@"json is %@",json); 

    [[NSUserDefaults standardUserDefaults] setValue:[json valueForKey:@"email"] forKey:@"fbemail"]; 
    [self.viewController login:YES]; 
} 
} 

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error 
{ 
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"" message:@"Server not responding.." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 

[alertView show]; 

[self fblogout]; 
[self showLoginView]; 
NSLog(@"request did fail with error"); 
} 


- (void)sessionStateChanged:(FBSession *)session 
         state:(FBSessionState) state 
         error:(NSError *)error 
{ 
switch (state) { 
    case FBSessionStateOpen: { 
     //state open action 
    } 

    // Initiate a Facebook instance 
    facebook = [[Facebook alloc] 
        initWithAppId:FBSession.activeSession.appID 
        andDelegate:nil]; 

    // Store the Facebook session information 
    facebook.accessToken = FBSession.activeSession.accessToken; 
    facebook.expirationDate = FBSession.activeSession.expirationDate; 

    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"fbemail"]) { 
    [MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES]; 
    [self getEmailId]; 
    } 

    break; 
    case FBSessionStateClosed: 
    case FBSessionStateClosedLoginFailed: 
    // Once the user has logged in, we want them to 
    // be looking at the root view. 
    [self.navController popToRootViewControllerAnimated:NO]; 

    [FBSession.activeSession closeAndClearTokenInformation]; 
    facebook = nil; 

    [self showLoginView]; 
    break; 
    default: 
    break; 
} 

[[NSNotificationCenter defaultCenter] 
    postNotificationName:FBSessionStateChangedNotification 
    object:session]; 

if (error) { 
    UIAlertView *alertView = [[UIAlertView alloc] 
          initWithTitle:@"Error" 
          message:error.localizedDescription 
          delegate:nil 
          cancelButtonTitle:@"OK" 
          otherButtonTitles:nil]; 
    [alertView show]; 
} 
} 
1

당신이 작동 희망 사용하도록 FBConnect API를 사용

18

당신은 다음과 같은 코드를 사용하여이 작업을 수행 할 수 있습니다.

편집 : 페이스 북 SDK v4에 대한 업데이트 (2015년 4월 23일는)

이제 Faceboook 주요 변화와 새로운 SDK를 발표했다. 어떤 FBSession 클래스에서 사용되지 않습니다. 따라서 모든 사용자는 새로운 SDK 및 API로 마이그레이션 할 것을 제안합니다. 우리는 페이스 북 SDK v4를 통해 사용자 정보를 얻을 수있는 방법 내가 언급 한 아래의

:

if ([FBSDKAccessToken currentAccessToken]) { 
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil] 
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) { 
    if (!error) { 
    NSLog(@”fetched user:%@”, result); 
    } 
}]; 
} 

그러나 사용자 정보를 가져 오는 전에, 우리가 Documentation here에 설명 된대로 우리의 코드에 새로운 페이스 북 로그인을 통합 할 수 있습니다.

Here은 SDK v4의 변경 내역입니다. 나는 갱신을 위해 그것을 통해가는 것이 좋습니다.

+0

사용자 전화 번호를받는 방법은 무엇입니까? –

+0

항상 FBSessionStateClosedLoginFailed로 들어가는 이유 ... 왜 ...? –

+0

@RamaniAshish : 권한 문제 일 수 있습니다. Facebook 통합을 완료하려면 FB 개발자에서 작동하는 앱이 있어야합니다. 우리가 사용자 계정 세부 정보를 사용하려고 할 때 그는 사용자의 세부 정보에 액세스 할 수있는 권한을 제공해야합니다. 이 모든 일이 완벽하게 일어나는지 확인하십시오. 이것은 나를 포함한 많은 다른 사람들을 위해 작동해야합니다 :) – astuter

1
FBRequest *request = [FBRequest requestForMe]; 
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) { 
    if (!error) { 
     // handle successful response 
    } else if ([error.userInfo[FBErrorParsedJSONResponseKey][@"body"][@"error"][@"type"] isEqualToString:@"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session 
     NSLog(@"The facebook session was invalidated"); 
     [self logoutButtonTouchHandler:nil]; 
    } else { 
     NSLog(@"Some other error: %@", error); 
    } 
}]; 
3

정보를 추가하십시오.PLIST 파일 :

enter image description here

0

페이스 북은 현재 4.x를 자신의 SDK 버전을 업데이트했습니다

- (IBAction)btn_fb:(id)sender 
    { 
     if (!FBSession.activeSession.isOpen) 
      { 
       NSArray *_fbPermissions = @[@"email",@"publish_actions",@"public_profile",@"user_hometown",@"user_birthday",@"user_about_me",@"user_friends",@"user_photos",]; 

     [FBSession openActiveSessionWithReadPermissions:_fbPermissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error) 
     { 
      if (error) 
      { 
       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
       [alertView show]; 
      } 
      else if(session.isOpen) 
      { 
       [self btn_fb:sender]; 
      } 


     }]; 


     return; 
    } 


    [FBRequestConnection startWithGraphPath:@"me" parameters:[NSDictionary dictionaryWithObject:@"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos" forKey:@"fields"] HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) 
    { 
     { 
      if (!error) 
      { 
       if ([result isKindOfClass:[NSDictionary class]]) 
       { 
        NSLog(@"%@",result); 

       } 
      } 
     } 
    }]; 
} 
사용자의 프로필 정보를 가져 오려면 로그인 성공 후 그래프 API를 명시 적으로 호출해야합니다 ( 은 필수 사용 권한을 묻습니다).

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] 
    initWithGraphPath:@"/me" 
      parameters:@{ @"fields": @"id,name,email"} 
      HTTPMethod:@"GET"]; 
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) { 
    // Insert your code here 
}]; 
관련 문제