Получить информацию о профиле Facebook iOS6

Я успешно попросил пользователей предоставить разрешение Facebook, используя метод, описанный ниже, через SocialFramework, но, похоже, не могу получить и затем отобразить основную информацию профиля (имя, адрес электронной почты, идентификатор и т. Д.). Я думаю, что есть простые методы для этого, но не могу их найти. Кто-нибудь может здесь помочь? Спасибо

-(IBAction)getInfo:(id)sender{

NSLog(@"FIRING");

ACAccountStore *_accountStore = [[ACAccountStore alloc] init];

ACAccountType *facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

// We will pass this dictionary in the next method. It should contain your Facebook App ID key,
// permissions and (optionally) the ACFacebookAudienceKey
NSDictionary *options = @{ACFacebookAppIdKey : @"284395038337404",
ACFacebookPermissionsKey : @[@"email"],
ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};

// Request access to the Facebook account.
// The user will see an alert view when you perform this method.
[_accountStore requestAccessToAccountsWithType:facebookAccountType
                                       options:options
                                    completion:^(BOOL granted, NSError *error) {
                                        if (granted)
                                        {
                                            NSLog(@"GRANTED");
                                            // At this point we can assume that we have access to the Facebook account
                                            NSArray *accounts = [_accountStore accountsWithAccountType:facebookAccountType];

                                            // Optionally save the account
                                            [_accountStore saveAccount:[accounts lastObject] withCompletionHandler:nil];
                                        }
                                        else
                                        {
                                            NSLog(@"Failed to grant access\n%@", error);
                                        }
                                    }];

}

1 ответ

С помощью кода, который вы разместили, вы можете получить доступ только к самой базовой информации об аккаунте, который вы получаете, в качестве псевдонима или описания, в данном случае это Facebook...

Пример:

ACAccount *account = [accounts lastObject];
NSString *username = account.username;

Чтобы получить более полную информацию, такую ​​как настоящее имя, адрес электронной почты и т. Д., Вам нужно сделать SLRequest с помощью функции / me графика api facebook.

NSURL *requestURL = [NSURL URLWithString:@"https://graph.facebook.com/me"];
NSString *serviceType = SLServiceTypeFacebook;

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[queue setName:@"Perform request"];
[queue addOperationWithBlock:^{

    SLRequest *request = [SLRequest requestForServiceType:serviceType requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];

    [request setAccount:account];

    NSLog(@"Token: %@", account.credential.oauthToken);

    [request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {

        // Handle the response...
        if (error) {
            NSLog(@"Error: %@", error);
            //Handle error
        }
        else {

            NSDictionary* jsonResults = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if (error) {

                NSLog(@"Error: Error serializating object");
                //Handle error
            }
            else {

                    NSDictionary *errorDictionary = [jsonResults valueForKey:@"error"];

                    if (errorDictionary) {

                        NSNumber *errorCode = [errorDictionary valueForKey:@"code"];

                        //If we get a 190 code error, renew credentials
                        if ([errorCode isEqualToNumber:[NSNumber numberWithInt:190]]) {

                            NSLog(@"Renewing credenciales...");

                            [self.accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){

                                if (error) {
                                    NSLog(@"Error: %@", error);
                                    //Handle error
                                }
                                else {
                                    if (renewResult == ACAccountCredentialRenewResultRenewed) {
                                        //Try it again
                                    }
                                    else {
                                        NSLog(@"Error renewing credenciales...");

                                        NSError *errorRenewengCredential = [[NSError alloc] initWithDomain:@"Error reneweng facebook credentials" code:[errorCode intValue] userInfo:nil];

                                        if (renewResult == ACAccountCredentialRenewResultFailed) {
                                            //Handle error
                                        }
                                        else if (renewResult == ACAccountCredentialRenewResultRejected) {
                                            //Handle error
                                        }
                                    }
                                }
                            }];
                        }
                    }
                    else {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"jsonResults: %@", jsonResults);
                        }];
                    }
                }
            }
        }
    }];
}];

Этот код также проверяет возможность ошибок, некоторую обработку, если токен истек и запускает сетевые процессы в фоновом режиме, чтобы не блокировать интерфейс.

Вы найдете всю информацию в словаре jsonResults, и вы можете получить доступ к ним следующим образом:

NSString *name = [jsonResults objectForKey:@"first_name"];
NSString *lastName = [jsonResults objectForKey:@"last_name"];
NSString *email = [jsonResults objectForKey:@"email"];

Проверьте документацию Facebook для получения дополнительной информации по адресу: https://developers.facebook.com/docs/reference/api/user/

Надеюсь, поможет!

Другие вопросы по тегам