Ios 如何从Facebook获取用户数据?

Ios 如何从Facebook获取用户数据?,ios,objective-c,iphone,Ios,Objective C,Iphone,我是iOS开发的新手,我正在尝试从Facebook获取用户的详细信息。这是我使用的代码,但当它调用时,我的应用程序是挂起的。在下面的代码中,当我无法在设置>Facebook中使用设备登录Facebook时,它无法工作。请帮我做这个 -(Void)LoginWithFB { ACAccountStore *accountStore = [[ACAccountStore alloc] init]; ACAccountType *facebookAccountType = [a

我是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];
    }
    }];
}
-(无效)登录WithfB{
ACAccountStore*accountStore=[[ACAccountStore alloc]init];
ACAccountType*facebookAccountType=[accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
SLComposeViewController*vc=[SLComposeViewController ComposeViewController服务类型:SLServiceTypeFacebook];
id选项=@{
ACFacebookAppIdKey:@“1501842240102594”,
ACFacebookPermissionsKey:@[@“电子邮件”],
};
[accountStore requestAccessToAccountsWithType:facebookAccountType
选项:选项
完成:^(已授予布尔,N错误*错误){
如果(授予)
{
//返回已登录的facebook帐户
ACAccount*fbAccount=[[accountStore accountsWithAccountType:facebookAccountType]lastObject];
//做你想做的。。。
//请求好友列表
//http://graph.facebook.com/000000000/picture
SLRequest*friendsListRequest=[SLRequestRequestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:[[NSURL alloc]initWithString:@”https://graph.facebook.com/me“]参数:无];
friendsListRequest.account=fbAccount;
[FriendsListRequestPerformRequestWithHandler:^(NSData*responseData,NSHTTPURLRResponse*URLRResponse,NSError*错误){
//解析响应JSON
n错误*jsonError=nil;
NSDictionary*dictionaryForFacebookData=[NSJSONSerialization JSONObjectWithData:responseData
选项:NSJSONReadingAllowFragments
错误:&jsonError];
//NSString*proficePicture=[NSString stringWithFormat:@]http://graph.facebook.com/415790901901979/picture"];
NSMutableDictionary*dictionaryParameter=[[NSMutableDictionary alloc]init];
[dictionaryParameter setObject:@“facebook”forKey:@“registrationsource”];
[dictionaryParameter设置对象:[dictionaryForFacebookData对象forKey:@“first_name”]forKey:@“firstname”];
[dictionaryParameter设置对象:[dictionaryForFacebookData对象forKey:@“last_name”]forKey:@“lastname”];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:@“电子邮件”]forKey:@“电子邮件”];
[dictionaryParameter setObject:@“是”forKey:@“状态”];
WebServiceClass*objectToCallApi=[[WebServiceClass alloc]init];
NSDictionary*dictionaryReturnValue=[objectToCallApi callAPIWebservice:dictionaryParameter stringURL:[[Singleton sharedInstance]passMethodName:@“login]”;
如果(![[dictionaryReturnValue objectForKey:@“success”]IseQualString:@“1”])
{
[UIAlertView showWithTitle:ALERT\u标题消息:[dictionaryReturnValue objectForKey:@“message”]处理程序:^(UIAlertView*alertview,NSInteger按钮索引){
}];
}
if([[dictionaryReturnValue objectForKey:@“success”]IseQualtString:@“1”])
{
APP_DELEGATE.intTabbarNumber=0;
NSMutableDictionary*数据=[[NSMutableDictionary alloc]init];
[数据集对象:[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”];
NSMUTABLEARRY*arrayOfExistingUser;
如果([[NSUserDefaults standardUserDefaults]valueForKey:@“Users”!=nil)
{
arrayOfExistingUser=[[[NSUserDefaults standardUserDefaults]valueForKey:@“用户”]可变副本];

对于方法签名中的(int i=0;i-(Void)LoginWithFB;Void不是一种类型,但Void是。因此这可能是问题所在。

在.h文件中
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);
        }
    }];


}
#进口 #进口 @属性(非原子,强)ACAccountStore*accountStore; @属性(非原子,强)ACAccount*facebookAccount; 在.m文件中 -(void)getuserdetails { self.accountStore=[[ACAccountStore alloc]init]; ACAccountType*FBaccountType=nil; //[self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook]; 如果(!FBaccountType){ FBaccountType=[\u accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook]; } NSString*key=kFBAppId; NSDictionary*dictFB=[NSDictionary Dictionary WithObjectsAndKeys:key,ACFacebookAppIdKey,@[@“电子邮件”],ACFacebookPermissionsKey,无]; [self.accountStore requestAccessToAccountsWithType:FBaccountType选项:dictFB完成: ^(已批准,N错误*e) { 如果(授予) { NSArray*accounts=[self.accountStore accountsWithAccountType:FBaccountType]; self.facebookAccount=[accounts lastObject]; NSLog(@“facebook帐户=%@”,self.facebook帐户); [自我获取]; } 其他的 { NSLog(@“fb错误%@”,如说明); dispatch\u async(dispatch\u get\u main\u queue()^ { [self-performSelectorOnMainThread:@selector(hideLoader)with object:nil waitUntilDone:YES];