简体   繁体   中英

iOS - getting user's Facebook profile picture

I want to get user's profile picture from Facebook in my app. I am aware of the http request that returns the profile picture:

http://graph.facebook.com/USER-ID/picture?type=small

But for that I need the user-id of my user. Is there a way to fetch that from somewhere without using the Facebook SDK? If not, can someone show me a simple way to get the user's id (or the profile picture)?

try this... it's working fine in my code .. and without facebook id you cant get ..

and one more thing you can also pass your facebook username there..

 //facebookID = your facebook user id or facebook username both of work well
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large&return_ssl_resources=1", facebookID]]; 
NSData *imageData = [NSData dataWithContentsOfURL:pictureURL];
UIImage *fbImage = [UIImage imageWithData:imageData];

Thanks ..

For getting FacebookId of any user, you will have to integrate Facebook Sdk from where you need to open session allow user to login in to Facebook (If user is already logged in to Facebook app, then it will just take permission from user to get access of the permission). Once you does that, you will get user details of logged in user from where you can get his FacebookId.

For more details please check developers.facebook.com.

In order to get the profile picture you need to know the Facebook user ID of the user. This can be obtained logging into Facebook with Social.framework (if you don't want to use Facebook SDK).

You can use ACAccountStore to request access to user's Facebook account like this:

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

ACAccountType *facebookTypeAccount = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

[accountStore requestAccessToAccountsWithType:facebookTypeAccount
                                       options:@{ACFacebookAppIdKey: YOUR_APP_ID_KEY, ACFacebookPermissionsKey: @[@"email"]}
                                    completion:^(BOOL granted, NSError *error) {
                                        ...

Please refer to instructions already answered in this post .

For information regarding how to obtain a Facebook App ID key (YOUR_APP_ID_KEY), look at Step 3 in this article .

Though it's an older question, the same you can do with iOS SDK 4.x like:

Swift:

    let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture?type=large&redirect=false", parameters: nil)
    pictureRequest.startWithCompletionHandler({
        (connection, result, error: NSError!) -> Void in
        if error == nil {
            println("\(result)")
        } else {
            println("\(error)")
        }
    })

Objective-C:

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                  initWithGraphPath:[NSString stringWithFormat:@"me/picture?type=large&redirect=false"]
                                  parameters:nil
                                  HTTPMethod:@"GET"];
    [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                          id result,
                                          NSError *error) {
    if (!error){
       NSLog(@"result: %@",result);}
    else {
       NSLog(@"result: %@",[error description]);
     }}];

The answer is:

https://graph.facebook.com/v2.4/me?fields=picture&access_token=[yourAccessToken]

if your token is abcdef then url will be:

https://graph.facebook.com/v2.4/me?fields=picture&access_token=acbdef

According to API explorer

you can use this link

https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Dpicture&version=v2.4

then if you want to get code for any platform make this:

go to the end of page and press "Get Code" button

在此处输入图片说明

then in appeared dialog choose your platform

在此处输入图片说明

and you will see the code

The following solution gets both essential user information and full size profile picture in one go... The code uses latest Swift SDK for Facebook(facebook-sdk-swift-0.2.0), integrated on Xcode 8.3.3

import FacebookCore import FacebookLogin

@IBAction func loginByFacebook(_ sender: Any) {

     let loginManager = LoginManager()
        loginManager.logIn([.publicProfile] , viewController: self) { loginResult in
        switch loginResult {
        case .failed(let error):
            print(error)
        case .cancelled:
            print("User cancelled login.")
        case .success(let grantedPermissions, let declinedPermissions, let accessToken):
            print("Logged in!")

            let authenticationToken = accessToken.authenticationToken
            UserDefaults.standard.set(authenticationToken, forKey: "accessToken")

            let connection = GraphRequestConnection()
            connection.add(GraphRequest(graphPath: "/me" , parameters : ["fields" : "id, name, picture.type(large)"])) { httpResponse, result in
                switch result {
                case .success(let response):
                    print("Graph Request Succeeded: \(response)")
                /* Graph Request Succeeded: GraphResponse(rawResponse: Optional({
                 id = 10210043101335033;
                 name = "Sachindra Pandey";
                 picture =     {
                 data =         {
                 "is_silhouette" = 0;
                 url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/13731659_10206882473961324_7366884808873372263_n.jpg?oh=f22b7c0d1c1c24654d8917a1b44c24ad&oe=5A32B6AA";
                 };
                 };
                 }))
                */

                    print("response : \(response.dictionaryValue)")



                case .failed(let error):
                print("Graph Request Failed: \(error)")
                }
            }
            connection.start()
        }
    }
}

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