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

34

我已经阅读了很多有关从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个回答

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: < value >
  • height: < value >
    • 同时使用widthheight来获取剪裁、等比缩放的图像

我需要在此代码之前做些什么吗?因为当我按下按钮时,它没有进入if语句。 - Le'Kirdok
好的,根据SDK教程(https://developers.facebook.com/docs/ios/ios-sdk-tutorial/)中所述,有一些初始化工作需要完成。我假设您已经按照这些步骤进行了操作。 - Guilherme
1
我想我做对了 :)。我从Facebook得到了一个应用程序ID,并将其写入了.plist文件。这些足够了吗?还是在获取信息之前需要先登录? - Le'Kirdok
设置Facebook SDK有一定的技巧。如果你已经设置了你的应用程序ID,请继续进行登录教程(https://developers.facebook.com/docs/ios/login-tutorial/),然后你就可以准备拉取用户数据了。 - Guilherme
2
请注意,不是所有用户都有用户名,在这种情况下,您不能使用名称,因为它可能会产生歧义。相反,您可以使用用户的ID来创建URL。 - Omer
显示剩余6条评论

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

谢谢,以下是Facebook文档的链接: https://developers.facebook.com/docs/ios/graph#fetching - HamzaGhazouani
1
而不是[[NSURL alloc] initWithURL: imageStringOfLoginUser];,应该使用[[NSURL alloc] initWithString: imageStringOfLoginUser];或更简单的NSURL *url = [NSURL URLWithString:imageStringOfLoginUser]; - rafalkitta

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) 对我来说行不通。


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;

你可以只保留图片和用户名参数,根据你的要求排除其他参数。希望对你有所帮助。

谢谢!比起发出两个请求,这种方法简单多了。 - Lena Bru

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

实际上我找到了更好的方法,你可以创建一个键为“fields”,值为“id,email,first_name,...,picture.type(large)”的字典-> 然后将其传递给参数(而不是nil)-> 然后你将得到图片信息以及其他所有信息。 - Islam
@IslamQ。你在哪里找到这个信息的?我想知道我还能在“字段”中添加什么。 - Damasio

0

实际上,使用 "http://graph.facebook.com//picture?type=small" 获取用户或其朋友的个人资料图片是很慢的。

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

例如: FBProfilePictureView *friendsPic;

friendsPic.profileID = @"1379925668972042";


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接