如何从 Facebook 获取用户数据?

How to get User Data from Facebook?

我是 iOS 开发的新手,我正在尝试从 Facebook 获取用户的详细信息。这是我使用的代码,但是当它调用我的应用程序时挂起。在下面的代码中,当我无法在设置 > Facebook 中使用 Facebook 中的设备登录时,它无法工作。请帮助我。

    -(Void)LoginWithFB {
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
    SLComposeViewController *vc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    id options = @{
               ACFacebookAppIdKey: @"1501842240102594",
               ACFacebookPermissionsKey: @[ @"email"],

               };
    [accountStore requestAccessToAccountsWithType:facebookAccountType
                                      options:options
                                   completion:^(BOOL granted, NSError *error) {
    if (granted)
    {
        // Return back logined facebook Account
        ACAccount *fbAccount = [[accountStore accountsWithAccountType:facebookAccountType] lastObject];

        // Do What you want...
        // Request friend list
        //http://graph.facebook.com/000000000/picture
        SLRequest *friendsListRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                        requestMethod:SLRequestMethodGET
                                        URL: [[NSURL alloc] initWithString:@"https://graph.facebook.com/me"]parameters:nil];
                                        friendsListRequest.account = fbAccount;
                                        [friendsListRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {

        // Parse response JSON
        NSError *jsonError = nil;
        NSDictionary *dictionaryForFacebookData = [NSJSONSerialization JSONObjectWithData:responseData
                                                   options:NSJSONReadingAllowFragments
                                                   error:&jsonError];

        //    NSString *proficePicture = [NSString stringWithFormat:@"http://graph.facebook.com/415790901901979/picture"];

            NSMutableDictionary *dictionaryParameter = [[NSMutableDictionary alloc]init];
            [dictionaryParameter setObject:@"facebook" forKey:@"registrationsource"];
            [dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:@"first_name"] forKey:@"firstname"];
            [dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:@"last_name"] forKey:@"lastname"];
            [dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:@"email"] forKey:@"email"];
            [dictionaryParameter setObject:@"yes" forKey:@"status"];

            WebServiceClass *objectToCallApi = [[WebServiceClass alloc]init];
            NSDictionary *dictionaryReturnValue = [objectToCallApi callAPIWebservice:dictionaryParameter stringURL:[[Singelton sharedInstance] passMethodName:@"login"]];
            if (![[dictionaryReturnValue objectForKey:@"success"] isEqualToString:@"1"])
            {
                [UIAlertView showWithTitle:ALERT_TITLE message:[dictionaryReturnValue objectForKey:@"message"] handler:^(UIAlertView *alertview, NSInteger buttonindex){
                }];
            }

            if ([[dictionaryReturnValue objectForKey:@"success"] isEqualToString:@"1"])
            {
                    APP_DELEGATE.intTabbarNumber = 0;
                NSMutableDictionary *data =[[NSMutableDictionary alloc]init];
                [data setObject:[NSString stringWithFormat:@"%@ %@",[dictionaryReturnValue objectForKey:@"firstname"], [dictionaryReturnValue objectForKey:@"lastname"]] forKey:@"fullname"];
                [data setObject:dictionaryReturnValue[@"username"] forKey:@"username"];
                [data setObject:dictionaryReturnValue[@"email"] forKey:@"email"];
                [data setObject:dictionaryReturnValue[@"userid"] forKey:@"userid"];
                 NSMutableArray *arrayOfExistingUser;
                if([[NSUserDefaults standardUserDefaults] valueForKey:@"Users"] != nil)
                {
                    arrayOfExistingUser = [[[NSUserDefaults standardUserDefaults] valueForKey:@"Users"] mutableCopy];
                    for (int i=0; i<arrayOfExistingUser.count; i++)
                    {
                        if ([[[arrayOfExistingUser objectAtIndex:i]objectForKey:@"userid"] isEqualToString:[data objectForKey:@"userid"]])
                        {
                            [arrayOfExistingUser removeObjectAtIndex:i];
                        }
                    }
                }
                else
                {
                    arrayOfExistingUser = [[NSMutableArray alloc]init];
                }

                [arrayOfExistingUser addObject:data];
                [[NSUserDefaults standardUserDefaults] setObject:arrayOfExistingUser forKey:@"Users"];
                [[NSUserDefaults standardUserDefaults] synchronize];

                [[NSUserDefaults standardUserDefaults]setObject:dictionaryReturnValue forKey:@"dictionaryForLoginData"];

                if ([[dictionaryReturnValue objectForKey:@"role"] isEqualToString:@"teacher"])
                {
                    [APP_DELEGATE createTabbarInstanceForTeacher];
                }
                else if ([[dictionaryReturnValue objectForKey:@"role"] isEqualToString:@"student"])
                {
                    [APP_DELEGATE createTabbarInstanceForstudent];
                }
                else if ([[dictionaryReturnValue objectForKey:@"role"] isEqualToString:@"parent"])
                {
                    [APP_DELEGATE createTabbarInstanceForParent];
                }
            }
            }];
            }
    else
    {
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        [controller.view resignFirstResponder];
        controller.view.hidden = YES;

        [self presentViewController:controller animated:NO completion:nil];
    }
    }];
}

在你的方法签名中- (Void)LoginWithFB; Void 不是类型,但 void 是。所以这可能是问题所在。

in .h file

#import <Accounts/Accounts.h>
#import <Social/Social.h>

@property (nonatomic, strong) ACAccountStore *accountStore;
@property (nonatomic, strong) ACAccount *facebookAccount;

in .m file 

- (void) getuserdetails
{

    self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= nil;
    //[self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    if (! FBaccountType) {
        FBaccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
    }
    NSString *key =kFBAppId;
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"email"],ACFacebookPermissionsKey, nil];


    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e)
     {
         if (granted)
         {
             NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
             self.facebookAccount = [accounts lastObject];
             NSLog(@"facebook account =%@",self.facebookAccount);
             [self get];
         }
         else
         {
             NSLog(@"fb error %@",e.description);

             dispatch_async(dispatch_get_main_queue(), ^
                            {
                                [self performSelectorOnMainThread:@selector(hideLoader) withObject:nil waitUntilDone:YES];
                                NSLog(@"%@",e.description);
                                if([e code]== ACErrorAccountNotFound)
                                {
                                    UIAlertView* alt = [[UIAlertView alloc] initWithTitle:@"Account not found"
                                                                                  message:msgSetUpFBAccount delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
                                    [alt show];
                                }
                                else
                                {
                                    UIAlertView* alt = [[UIAlertView alloc] initWithTitle:msgFBAccessDenied
                                                                                  message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
                                    [alt show];
                                }

                            });
             NSLog(@"error getting permission %@",e);

         }
     }];
}

-(void)get
{

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

    SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                            requestMethod:SLRequestMethodGET
                                                      URL:requestURL
                                               parameters:nil];
    request.account = self.facebookAccount;
    [request performRequestWithHandler:^(NSData *data,
                                         NSHTTPURLResponse *response,
                                         NSError *error)
     {

         if(!error)
         {
             list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

             NSLog(@"Dictionary contains: %@", list );


             if([list objectForKey:@"error"]!=nil)
             {
                 [self attemptRenewCredentials];
             }
             dispatch_async(dispatch_get_main_queue(),^{
             });

         }
         else
         {
             [self performSelectorOnMainThread:@selector(hideLoader) withObject:nil waitUntilDone:YES];
             NSLog(@"error from get%@",error);
         }

     }];


}



-(void)attemptRenewCredentials{
    [self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
        if(!error)
        {
            switch (renewResult) {
                case ACAccountCredentialRenewResultRenewed:
                    NSLog(@"Good to go");

                    [self get];
                    break;
                case ACAccountCredentialRenewResultRejected:
                {
                    NSLog(@"User declined permission");
                    UIAlertView* alt = [[UIAlertView alloc] initWithTitle:@"Access Denied"
                                                                  message:@"You declined permission" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
                    [alt show];
                    break;
                }
                case ACAccountCredentialRenewResultFailed:
                {
                    NSLog(@"non-user-initiated cancel, you may attempt to retry");
                    UIAlertView* alt = [[UIAlertView alloc] initWithTitle:@"Access Denied"
                                                                  message:@"non-user-initiated cancel, you may attempt to retry" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
                    [alt show];
                    break;
                }
                default:
                    break;
            }

        }
        else{
            //handle error gracefully
            NSLog(@"error from renew credentials%@",error);
        }
    }];


}