从Facebook iOS 7获取用户名和个人资料图片

时间:2013-12-17 00:30:43

标签: ios objective-c facebook facebook-graph-api

我已经阅读了很多关于从Facebook获取信息的教程,但到目前为止我都失败了。我只是想从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;
       }

   } ];


 }

我使用此代码获取信息,但我无法获取任何信息。 你能帮我解决一下吗?或者你更喜欢阅读教程吗?我已经阅读了developer.facebook.com上的教程。

感谢您的关注。

7 个答案:

答案 0 :(得分:80)

这是我发现获取用户个人资料照片的最简单方法。

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

可以使用的其他查询参数是:

  • type :small,normal,large,square
  • width :&lt;值&gt;
  • 身高:&lt;值&gt;
    • 同时使用 width height 来获取裁剪的宽高比填充图像

答案 1 :(得分:38)

$result = array();
while ($row = fetch()) {
    $result[] = $row;
}
echo json_encode($result);

答案 2 :(得分:6)

发出以下图表请求:

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

你会得到非常大而酷的个人资料:

{
  "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)并不适合我。

答案 3 :(得分:5)

您还可以按如下方式获取用户名和图片:

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

你可以把参数留给图片&amp;用户名并根据您的要求排除其他用户名。 HTH。

答案 4 :(得分:1)

这是Facebook SDK 4和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)
            }
        }
    })
}

更新回答问题:

要下载公开个人资料图片,您可以从字典中获取Facebook ID:

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

然后使用Facebook ID:

调用图表API以获取个人资料图片的请求
let pictureURL = "https://graph.facebook.com/\(fbUserId)/picture?type=large&return_ssl_resources=1"

示例代码:

    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)")
        }
    })

答案 5 :(得分:0)

实际上使用“http://graph.facebook.com/ / picture?type = small”来获取用户的个人资料图片甚至他们的朋友都很慢。

更好更快的方法是将FBProfilePictureView对象添加到视图及其profileID属性中,分配用户的Facebook ID。

例如:  FBProfilePictureView * friendsPic;

friendsPic.profileID = @“1379925668972042”;

答案 6 :(得分:0)

看看这个lib: https://github.com/jonasman/JNSocialDownload

你甚至可以获得推特