2013-12-17 182 views
34

我已經閱讀了很多關於從Facebook獲取信息的教程,但目前爲止我失敗了。我只想從Facebook獲取用戶名和個人資料照片。從Facebook獲取用戶名和個人資料圖片iOS 7

- (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上的教程。

謝謝您的關注。

回答

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

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

  • 類型:小,正常的,大的,正方形
  • 寬度:<值>
  • 高度: <價值>
    • 使用兩個寬度高度得到裁剪,縱橫填圖像
+0

我需要這一代碼之前做一些事情?因爲當我點擊按鈕時,它不會去if語句。 –

+0

那麼,SDK教程(https://developers.facebook.com/docs/ios/ios-sdk-tutorial/)中介紹了一些初始化。我假設你已經遵循了這些步驟。 – Guilherme

+1

我想我做到了:)。我從Facebook獲得了一個appID,並且我在.plist文件中寫了這些。這些足夠了,還是需要在提取信息之前先登錄? –

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; 

你可以見好就收參數&用戶名並根據您的要求排除其他參數。 HTH。

+0

謝謝!比提出2個請求更簡單的方法 –

0

實際使用「http://graph.facebook.com/ /圖片?類型=小」來抓取用戶,甚至他們的朋友的個人資料圖片是緩慢的。

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

例如: FBProfilePictureView * friendsPic;

friendsPic.profileID = @「1379925668972042」;

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

附: /me?fields=picture.type(large)不適合我。

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

UPDATE回答問題:

要下載公開個人資料圖片,請從字典中獲取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)") 
     } 
    }) 
+0

個人資料圖片怎麼樣? –

+0

其實我找到了一個更好的方法,你可以用鍵「** fields **」和值「** id,email,first_name,...,picture.type(large)** 「 - >然後通過參數(而不是零) - >然後你會得到圖片信息以及其他一切。 –

+0

@IslamQ。你在哪裏找到這些信息?我想知道我還能在「字段」中添加什麼內容。 – Damasio

36
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]; 
     } 
    }]; 
} 
+0

它適用於新的Facebook SDK v2.3 –

+0

謝謝,它適用於最新的facebook SDK。 –

+0

謝謝,下面的鏈接到Facebook文檔: https://developers.facebook.com/docs/ios/graph#fetching –

相關問題