簡體   English   中英

從Facebook iOS 7獲取用戶名和個人資料圖片

[英]Getting username and profile picture from Facebook iOS 7

我讀了很多關於從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上的教程。

感謝您的關注。

這是找到用戶個人資料圖片的最簡單方法。

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

可以使用的其他查詢參數是:

  • 類型 :小,普通,大,正方形
  • 寬度 :<值>
  • 高度 :<值>
    • 同時使用寬度高度來獲取裁剪的縱橫比填充圖像
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];
        }
    }];
}

發出以下圖形請求:

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

PS /me?fields=picture.type(large)對我來說不行。

您還可以按以下方式獲取用戶名和圖片:

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

您可以僅將參數保留為圖片和用戶名,並根據您的要求排除其他參數。 HTH。

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

實際使用“ http://graph.facebook.com/ / picture?type = small”來獲取用戶甚至他們的朋友的個人資料圖片的速度很慢。

將FBProfilePictureView對象添加到視圖的一種更好,更快的方法,並在它的profileID屬性中分配用戶的Facebook ID。

例如:FBProfilePictureView * friendsPic;

friendsPic.profileID = @“ 1379925668972042”;

看看這個庫: https : //github.com/jonasman/JNSocialDownload

你甚至可以得到推特

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM