简体   繁体   中英

Fetch user data from Facebook on iOS

I am new to iOS I just want to get info such as gender, city, e-mail, and date of birth

but from code which I posted below ,I just got an idea like how to post data on Facebook,

now I want to fetch user details form Facebook

.h

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

@interface ViewController : UIViewController
- (IBAction)PostFB:(id)sender;
- (IBAction)PostTW:(id)sender;

@end

.m

//
//  ViewController.m
//  FaceBookFirstApp3
//
//  Created by hits1 on 27/01/14.
//  Copyright (c) 2014 hits1. All rights reserved.
//

#import "ViewController.h"
#import <Social/Social.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)PostFB:(id)sender {

    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
    {
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [controller setInitialText:@"First post from my iPhone app"];

        [self presentViewController:controller animated:YES completion:Nil];
    }
}

- (IBAction)PostTW:(id)sender {

    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:@"Great fun to learn iOS programming at appcoda.com!"];
        [tweetSheet addURL:[NSURL URLWithString:@"http://www.appcoda.com"]];
        [tweetSheet addImage:[UIImage imageNamed:@"socialsharing-facebook-image.jpg"]];
        [self presentViewController:tweetSheet animated:YES completion:nil];
    }



}
@end

please, help me Out to Fetch at least one field(city (or) gender (or) phone-number) form Gmail or Facebook

You can use the below code to get user's gender, city, e-mail, and date of birth

In .h file add,

#import <Accounts/Accounts.h>
@property (nonatomic, retain) ACAccountStore *accountStore;
@property (nonatomic, retain) ACAccount *facebookAccount;
-(void)get;
-(void)attemptRenewCredentials;
- (void) getuserdetails;

in .m file

- (void) getuserdetails
{

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

  NSString *key = @"your app id";
  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 {
         dispatch_async(dispatch_get_main_queue(), ^{

            // NSLog(@"%@",e.description);
             if([e code]== ACErrorAccountNotFound)
             {
                 UIAlertView* alt = [[UIAlertView alloc] initWithTitle:@"Account not found"
                                                               message:@"Please setup your Facebook account in Settings App" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
                 [alt show];
             }
             else
             {
                 UIAlertView* alt = [[UIAlertView alloc] initWithTitle:@"Access Denied"
                                                               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 );
        NSLog(@"EmailID %@",[list objectForKey:@"email"]);

        NSLog(@"Birthday %@",[list objectForKey:@"birthday"]);
        NSLog(@"Gender %@",[list objectForKey:@"gender"]);

        NSLog(@"City %@",[[list objectForKey:@"location"] objectForKey:@"name"]);


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

    }
    else{
        //handle error gracefully
        NSLog(@"error from get%@",error);
        //attempt to revalidate credentials
    }

}];


}

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


}

-(void)accountChanged:(NSNotification *)notif//no user info associated with this notif
{
[self attemptRenewCredentials];
}
- (void)sessionStateChanged:(NSNotification*)notification
{  
  if (FBSession.activeSession.isOpen)
  {
            [[FBRequest requestForMe] startWithCompletionHandler:
             ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
             {
                 if (!error)
                 {
                         //for geting the user detail.
                         NSString *fbSelectDetails = [@"" stringByAppendingFormat:@"https://graph.facebook.com/me? fields=id,name,email,first_name,last_name,gender,picture,link,birthday,quotes,education&access_token=%@",FBSession.activeSession.accessToken];

                         NSMutableDictionary *userDetails = [NSMutableDictionary dictionaryWithDictionary:[DataLayer getJSONContentFromURL:fbSelectDetails]];


                         NSString *uid = [userDetails valueForKey:@"id"];
                         NSString *userName= user.name;
                         NSString *userEmail=  [userDetails valueForKey:@"email"];
                         NSString *userFirstName=  [userDetails valueForKey:@"first_name"];
                         NSString *userLastName=  [userDetails valueForKey:@"last_name"];
                         NSString *userGender=  [userDetails valueForKey:@"gender"];
                         NSString *userLink=  [userDetails valueForKey:@"link"];
                         NSString *userDob=  [userDetails valueForKey:@"birthday"];

                         NSMutableDictionary *imgUrl = [NSMutableDictionary dictionaryWithDictionary:[userDetails valueForKey:@"picture"]];
                         NSString *userImgUrl= [[imgUrl valueForKey:@"data"] valueForKey:@"url"];
     }];
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM