2013-05-25 15 views
12

Sono nuovo nello sviluppo di iPhone. Sto facendo un'app in cui l'utente ha 2 login tramite Facebook, una volta che ha inviato le sue credenziali e clicca sul pulsante Accedi, devo recuperare dettagli come Nome, email e sesso da Facebook e dopo aver recuperato l'utente deve essere diretto alla pagina di registrazione dell'app con i dettagli riempiti e ho bisogno di questa app per essere compatibile con iPhone 4,4s e 5.Recupero dei dettagli utente da Facebook su iOS

Ho provato a farlo utilizzando l'API di Facebook Graph ma non ho potuto ottenerlo, quindi chiunque può aiutarmi.

Grazie in anticipo.

+3

Benvenuti in SO. Devi pubblicare ciò che hai provato. Cercheremo di aiutarti, ma solo dopo che avrai dimostrato che ci hai messo almeno un po 'di impegno. –

risposta

1
1

utilizzare l'API FBConnect per prendere information.its utente facile da usare

Fbconnect API

auguro che funziona per voi :)

1

avete utilizzare il percorso del grafico per ottenere le informazioni dell'utente.

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

È possibile farlo utilizzando seguente codice:

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

           } ]; 

e non si è dimenticato di importare FacebookSDK/FacebookSDK.h nel codice.

EDIT: Aggiornamento per Facebook SDK v4 (23 aprile 2015)

Ora, Faceboook hanno rilasciato il nuovo SDK con grandi cambiamenti. In quale classe FBSession è deprecata. Quindi tutti gli utenti sono invitati a migrare a nuovi sdk e API.

Qui di seguito ho detto, come possiamo ottenere i dettagli dell'utente tramite 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); 
    } 
}]; 
} 

Ma prima di andare a prendere i dettagli dell'utente, dobbiamo integrare nuovo account di accesso di Facebook nel nostro codice come descritto in Documentation here.

Here è il Changelog per SDK v4. Suggerisco di esaminarlo per essere aggiornato.

+0

come ottenere il numero di telefono dell'utente? –

+0

va sempre in FBSessionStateClosedLoginFailed ... Perché ...? –

+0

@RamaniAshish: potrebbe essere dovuto a problemi di autorizzazione. Per completare l'integrazione di Facebook, dobbiamo avere un'app funzionante nello sviluppatore FB. Quando proviamo a utilizzare i dettagli dell'account utente, deve fornire il permesso per accedere ai suoi dettagli. assicurati che tutto ciò stia accadendo perfettamente. Questo dovrebbe funzionare come funzionante per molti altri, incluso me :) – 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

Aggiungi informazioni.il file plist:

enter image description here

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

       } 
      } 
     } 
    }]; 
} 
0

Facebook ha attualmente aggiornato la loro versione SDK per 4.x. Per recuperare le informazioni del profilo dell'utente è necessario chiamare esplicitamente l'API del grafico dopo aver effettuato il login con successo (chiedere le autorizzazioni richieste).

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 
}]; 
Problemi correlati