Unity3D Facebook SDK for Android Integration - 4. 친구 리스트 얻기, 친구 프로필 이미지 출력

 유니티3D 페이스북 SDK 안드로이드 연동 관련 자신의 담벼락 게시 및 자신의 프로필 이미지 출력까지 해봤습니다. 이번 포스팅은 페이스북 친구 목록을 얻어와서 친구의 프로필 사진을 유니티3D로 렌더링하는 것까지 정리해보겠습니다.


1. 친구 목록 가져오기

public void requestFriends_U() {
runOnUiThread(new Runnable(){
public void run() {
Session session = Session.getActiveSession();
            Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() {

@Override
public void onCompleted(List<GraphUser> users,
Response response) {
// TODO Auto-generated method stub
if (users != null) {
JSONArray jsonArr = new JSONArray();

for (GraphUser user : users) {
Log.d("UnityFacebookTest", user.getName() + " " + user.getId());
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put("FacebookId", user.getId());
jsonObj.put("Name", user.getName());
jsonArr.put(jsonObj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

UnityPlayer.UnitySendMessage("FacebookManager", "ResultFriends_J", jsonArr.toString());
}
}
            });
}
});
}

 먼저 자바쪽입니다. Request.executeMyFriendsRequestAsync를 통해 친구 목록을 요청합니다. Request.GraphUserListCallback의 onCoompleted에서 친구 목록을 JSONObject로 만들어 JSONArray에 쌓고있죠. 마지막에는 유니티3D에 json을 스트링형으로 넘겨줍니다.

 결과부터 보면 위와같이 로그로 잘 찍혔습니다. 이제 유니티3D부분을 보겠습니다.

using LitJson;

private Dictionary<string, string> dicFriends;

void Awake()
{
  ...
  this.dicFriends = new Dictionary<string, string>();
}


public void RequestFriends()
{
curActivity.Call("requestFriends_U");
}

public void ResultFriends_J(string jsonFriends)
{
JsonData jData = JsonMapper.ToObject(jsonFriends);
for (int i = 0 ; i < jData.Count ; i++)
{
string strFacebookId = jData[i]["FacebookId"].ToString();
string strFacebookName = jData[i]["Name"].ToString();
Debug.Log("Friend id " + strFacebookId + " Name " + strFacebookName);
this.dicFriends.Add(strFacebookId, strFacebookName);
}
Debug.Log("Friend Count = " + this.dicFriends.Count.ToString());
}

 FacebookManager 컴포넌트에 추가된 부분입니다. 친구 목록을 스트링으로 받아와서 JSON 객체로 만든 후 Dictionary에 추가하고 있습니다. C#에서 JSON을 사용하기 위해 저는  LitJson을 사용했습니다. 링크를 참고하세요.


class Friend                        
{                                
public Texture2D texFriend = null;
public Rect rtTexPos;          
}                                
                                 
List<Friend> listFriend = null;  

void OnGUI()
{
...
fYpos += 50;                                                            
if (GUI.Button (new Rect(0, fYpos, 100, 50), "Get Friends\nList") == true)
{                                                                      
FacebookManager.GetInstance().RequestFriends();
}                                                                      
}

 TestGUI 컴포넌트 부분입니다.


2. 친구 프로필 사진 출력하기

 위 내용과 아래에 나올 GUI쪽 작업을 하면 위와 같이 생겼습니다. 이번에는 자바쪽은 없고 유니티3D쪽 C# 작업만 있습니다.

public Dictionary<string, string> GetFriends()
{
return this.dicFriends;
}

 쌓아둔 친구 목록을 통째로 가져오기 위해 FacebookManager 컴포넌트에 위와같은 함수를 추가합니다.


fYpos += 50;
if (GUI.Button (new Rect(0, fYpos, 100, 50), "Down Friends\nPic") == true)
{
StartCoroutine(DownFriendPic());
}

if (this.listFriend != null)
{
for ( int i = 0 ; i < this.listFriend.Count ; i++)
{
if (this.listFriend[i].texFriend != null)
GUI.DrawTexture(this.listFriend[i].rtTexPos, this.listFriend[i].texFriend);
}
}

 TestGUI 컴포넌트 OnGUI에 위와같이 친구의 사진을 다운로드할 버튼을 추가하고 친구 프로필 사진을 그려주는 GUI.DrawTexture를 추가합니다.


private IEnumerator DownFriendPic()                                                    
{                                                                                      
Dictionary<string, string> dicFriends;                                                
dicFriends = new Dictionary<string, string>(FacebookManager.GetInstance().GetFriends());
if (dicFriends.Count > 0)                                                            
{                                                                                    
Debug.Log ("Friends num " + dicFriends.Count.ToString());                          
                                                                                   
this.listFriend = new List<Friend>();                                              
                                                                                     
foreach (KeyValuePair<string, string> pair in dicFriends)                          
{                                                                                  
Friend friend = new Friend();                                                    
                                                                                 
yield return StartCoroutine( DownPic(pair.Key) );                                
                                                                                 
friend.rtTexPos = new Rect(                                                      
Random.Range(0, Screen.width)                                                  
, Random.Range(0, Screen.height)                                                
, 50, 50);                                                                      
friend.texFriend = curDownTex;                                                    
this.listFriend.Add(friend);                                                      
}                                                                                  
}                                                                                    
}

 코루틴을 사용해서 친구의 프로필 사진을 WWW로 다운받아 Texture2D에 저장합니다. 위치는 랜덤하게 잡아줬습니다.

 버튼을 누르면 친구 사진이 다운로드가 됩니다. 코루틴을 사용하기 때문에 비동기로 하나씩 렌더링이 되죠.

 친구 프로필 사진이 모두 그려진 상태입니다.

 유니티3D에 페이스북 안드로이드 연동 포스팅을 해봤습니다. 여기서 더 해나갈지는 두고봐야겠네요.

댓글

이 블로그의 인기 게시물

'xxx.exe' 프로그램을 시작할 수 없습니다. 지정된 파일을 찾을 수 없습니다.

goorm IDE에서 node.js 프로젝트로 Hello World Simple Server 만들어 띄워보기

애드센스 수익을 웨스턴 유니온으로 수표대신 현금으로 지급 받아보자.