34

I have read a lot of tutorials about getting information from Facebook, but I have failed so far. I just want to get username and profile picture from Facebook.

- (IBAction)login:(id)sender {

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

   } ];


 }

I used this code for get information, but I cannot get the any information. Can you help me about it? or Can you prefer a tutorial to read it? I have read tutorials on developer.facebook.com.

Thank you for your interest.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Kirdok
  • 1,904
  • 2
  • 22
  • 27

7 Answers7

80

This is the simplest way I've found to get the user's profile picture.

[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *FBuser, NSError *error) {
    if (error) {
      // Handle error
    }

    else {
      NSString *userName = [FBuser name];
      NSString *userImageURL = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", [FBuser objectID]];
    }
  }];

Other query parameters that can be used are:

  • type: small, normal, large, square
  • width: < value >
  • height: < value >
    • Use both width and height to get a cropped, aspect fill image
Guilherme
  • 7,839
  • 9
  • 56
  • 99
  • Do i need to do something before this code? Because when i hit the button, it isn't going to if statement. – Kirdok Dec 17 '13 at 00:49
  • Well, there's some initialization as described by the SDK tutorial (https://developers.facebook.com/docs/ios/ios-sdk-tutorial/). I was assuming you have followed those steps. – Guilherme Dec 17 '13 at 00:51
  • 1
    I think i did :). I got a appID from Facebook and i wrote in the .plist file.These are enough or do i need to login first before pull the information? – Kirdok Dec 17 '13 at 00:57
  • Setting up Facebook SDK is sort of tricky. If you've already setup your app ID, follow with the Login tutorial (https://developers.facebook.com/docs/ios/login-tutorial/), and then you should be ready to pull user data. – Guilherme Dec 17 '13 at 01:00
  • Thank you very much again. I tried it and it is working perfect. I was working on it for 3 days.Thanks again – Kirdok Dec 17 '13 at 13:34
  • 2
    Be careful, not all users have username, in that case you cannot use the name because it might be ambiguos. You can use the users's id instead to create the url – Omer Jun 12 '14 at 18:39
  • @Omer good point. Using the user ID should work in every case. Will edit my post. – Guilherme Jun 12 '14 at 23:52
  • Very clean. Nice answer! – inorganik Aug 29 '14 at 18:01
  • exactly what I wanted. – Prashant Nikam Sep 09 '14 at 08:04
  • Thanks Guilherme! Truely the simplest way of doing it. – Hashim Akhtar Dec 19 '14 at 17:05
  • @Guilherme, since FB SDK is constantly changing, you shoud edit your answer with its version number. This do not work anymore on v2.3 – Martin Sep 10 '15 at 09:59
38
if ([FBSDKAccessToken currentAccessToken]) {
    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{ @"fields" : @"id,name,picture.width(100).height(100)"}]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        if (!error) {
            NSString *nameOfLoginUser = [result valueForKey:@"name"];
            NSString *imageStringOfLoginUser = [[[result valueForKey:@"picture"] valueForKey:@"data"] valueForKey:@"url"];
            NSURL *url = [[NSURL alloc] initWithURL: imageStringOfLoginUser];
            [self.imageView setImageWithURL:url placeholderImage: nil];
        }
    }];
}
Augustin Jose
  • 350
  • 3
  • 12
Hemanshu Liya
  • 611
  • 6
  • 10
  • Thanks, below the link to the Facebook documentation : https://developers.facebook.com/docs/ios/graph#fetching – HamzaGhazouani Oct 20 '15 at 09:04
  • 1
    Instead ```[[NSURL alloc] initWithURL: imageStringOfLoginUser];``` should be ```[[NSURL alloc] initWithString: imageStringOfLoginUser];``` or easier ```NSURL *url = [NSURL URLWithString:imageStringOfLoginUser];``` – rafalkitta Feb 05 '16 at 12:35
6

Make the following Graph request:

/me?fields=name,picture.width(720).height(720){url}

And you get really large and cool profile picture:

{
  "id": "459237440909381",
  "name": "Victor Mishin", 
  "picture": {
    "data": {
      "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/t31.0-1/c628.148.1164.1164/s720x720/882111_142093815957080_669659725_o.jpg"
    }
  }
}

P.S. /me?fields=picture.type(large) doesn't do it for me.

Victor
  • 914
  • 12
  • 15
5

You could also get the username and picture as follows:

[FBSession openActiveSessionWithReadPermissions:@[@"basic_info"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {

             if(!error && state == FBSessionStateOpen) {
                 { [FBRequestConnection startWithGraphPath:@"me" parameters:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"id,name,first_name,last_name,username,email,picture",@"fields",nil] HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                             NSDictionary *userData = (NSDictionary *)result;
                             NSLog(@"%@",[userData description]);
                         }];
                 }
             }
         }];

Output:
picture =     {
        data =         {
            "is_silhouette" = 0;
            url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc1/t5.0-1/xxxxxxxxx.jpg";
        };
    };
    username = xxxxxxxxx;

You could just leave the parameter to picture & username and exclude the others based on you requirement. HTH.

batman
  • 1,937
  • 2
  • 22
  • 41
1

This is the code for Facebook SDK 4 and Swift:

if FBSDKAccessToken.currentAccessToken() != nil {
    FBSDKGraphRequest(graphPath: "me", parameters: nil).startWithCompletionHandler({ (connection, result, error) -> Void in
        println("This logged in user: \(result)")
        if error == nil{
            if let dict = result as? Dictionary<String, AnyObject>{
                println("This is dictionary of user infor getting from facebook:")
                println(dict)
            }
        }
    })
}

UPDATE TO ANSWER QUESTIONS:

To download public profile image, you get the facebook ID from the dictionary:

let facebookID:NSString = dict["id"] as AnyObject? as NSString

And then call a request to graph API for profile image using the facebook ID:

let pictureURL = "https://graph.facebook.com/\(fbUserId)/picture?type=large&return_ssl_resources=1"

Sample code:

    let pictureURL = "https://graph.facebook.com/\(fbUserId)/picture?type=large&return_ssl_resources=1"
    //
    var URLRequest = NSURL(string: pictureURL)
    var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
    println(pictureURL)



    NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
        if error == nil {
            //data is the data of profile image you need. Just create UIImage from it

        }
        else {
            println("Error: \(error)")
        }
    })
thomasdao
  • 972
  • 12
  • 26
  • Actually I found a better way, you can create a **dictionary** with the key "**fields**" and value "**id,email,first_name, ... , picture.type(large)**" -> then pass this in the parameters (instead of nil) -> then you'll get the picture info along with everything else. – Islam May 27 '15 at 05:28
  • @IslamQ. where did u find this information? I would like to know what else I can add in "fields". – Damasio Nov 09 '15 at 14:23
0

Actually using "http://graph.facebook.com//picture?type=small" to fetch the profile image of the user or even their friends is slow.

A better and faster way of doing it to add a FBProfilePictureView object to your view and in it's profileID property, assign the user's Facebook id.

For example: FBProfilePictureView *friendsPic;

friendsPic.profileID = @"1379925668972042";

Hashim Akhtar
  • 813
  • 2
  • 11
  • 16
0

Check out this lib: https://github.com/jonasman/JNSocialDownload

you can even get twitter

João Nunes
  • 3,751
  • 31
  • 32