2013-05-25 9 views
12

iPhone開発は初めてです。私は、ユーザーがFacebookからの2回のログインを持っているAppをやっている。クレデンシャルを送信してサインインボタンをクリックすると、FacebookからFirst name、email、genderのような詳細をフェッチする必要があり、フェッチした後、アプリケーションの登録ページに詳細が記入されています。このアプリはiPhone 4,4,5と互換性が必要です。iOSでFacebookからユーザーの詳細を取得する

私はFacebook Graph APIを使ってこれを試みましたが、誰もが私を助けてください。

ありがとうございました。

+3

ようこそ。あなたが試したことを投稿する必要があります。私たちはあなたを助けようとしますが、あなたがそれに少なくとも何らかの努力をしていることを示した後でなければなりません。 –

答えて

1

あなたが持っている使いやすいフェッチユーザーinformation.itsためFBConnectのAPIを使用してください....助けを願っていますグラフパスを使用してユーザー情報を取得する

[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]; 
} 
} 
18

次のコードを使用してこれを行うことができます。

EDIT:FacebookのSDK v4の用の更新プログラム(2015年4月23日)今

、Faceboookは大きな変化と新しいSDKをリリースしています。どのFBSessionクラスでは非推奨です。だから、すべてのユーザーは新しいsdkとAPIに移行するように提案されています。

私たちはFacebookの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で説明したように、私たちのコードで新しいFacebookのログインを統合する必要があります。

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

Facebookは現在、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 
}]; 
関連する問題