ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • FACEBOOK과 UNITY - 02 FacebookManager 만들기
    Unity/Facebook 2020. 6. 10. 07:21
            // 링크 공유 함수, 일반 링크처럼 올라간다.
            public void shareLink()
            {
                FB.ShareLink(new System.Uri(shareContentURL), shareTitle, shareDescription, new System.Uri(sharePictureURL), callback: shareCallback);
            }
    
            // 피드 공유 함수. 크게 다르지 않다. (링크만 하나 덜렁 올라간다.)
            public void shareFeed()
            {
                FB.FeedShare("", new System.Uri(shareContentURL), shareTitle, "LINK CAPTION", shareDescription, new System.Uri(sharePictureURL), "", callback: shareCallback);
            }
    
    
            // 공유하기 콜백 함수. 취소나 에러 등의 상태를 파악한다.
            protected virtual void shareCallback(IShareResult result)
            {
                if (result.Cancelled || !string.IsNullOrEmpty(result.Error))
                {
                    Debug.Log("ShareLink Error: " + result.Error);
                }
                else if (!string.IsNullOrEmpty(result.PostId))
                {
                    Debug.Log(result.PostId);
                }
                else
                {
                    Debug.Log("ShareLink success!");
                }
            }

    전반적으로 참조할 예제
    https://developers.facebook.com/docs/unity/examples

     

    Examples - Unity SDK - 문서 - Facebook for Developers

     

    developers.facebook.com

    퍼미션(Permission) 레퍼런스(References)

    https://developers.facebook.com/docs/permissions/reference/publish_pages

     

    publish_pages - 앱 개발 - 문서 - Facebook for Developers

    The publish_pages permission allows your app to publish posts, comments and like Pages managed by the app user.

    developers.facebook.com

     

    싱클턴 패턴을 사용하기 위해 만든 클래스.  

    Generic Singleton Class. where구문을 통해 Component를 상속받은 클래스(T)들만 이용할 수 있도록 제한을 걸었다.

    public class MySingleton<T> : MonoBehaviour where T : Component
        {
    		protected static T _instance;
    
    		public static T Instance
    		{
    			get
    			{
    				if (_instance == null)
    				{
    					_instance = FindObjectOfType<T>();
    					if (_instance == null)
    					{
    						GameObject obj = new GameObject();
    						_instance = obj.AddComponent<T>();
    					}
    				}
    				return _instance;
    			}
    		}
    
    		protected virtual void Awake()
    		{
    			if (!Application.isPlaying)
    			{
    				return;
    			}
    
    			_instance = this as T;
    		}
    	}

     

    https://www.youtube.com/watch?v=QVuVwTwKjxE

    꽤나 괜찮은 예제 Youtube

     

    영상과 달리, ShareLink를 해도 URL 링크만 전송될 뿐, Title이나 Description, ImageUrl을 설정하는 기능은 더 이상 통하지 않는다. 

     

    https://developers.facebook.com/docs/pages/publishing

     

    게시 - Pages - 문서 - Facebook for Developers

     

    developers.facebook.com

    안타깝게도 API를 통해 이미지를 직접 업로드하고 공유하는 기능이 불가능해진 것 같다.

     

    (공식 가이드 문서 상에서는 ImageURL을 통해 Post를 작성하고 있다.)

     

    아무튼 되지도 않는 기능 왜 안되나 싶어서 Debug하는 바람에 한참을 헤매었다.

     

     

     

    앱 초기화 부분 - 사실 앱 초기화 하는 부분은 크게 별거 없다.

            // 초기화 함수
            public void initialize()
            {
                if (!FB.IsInitialized)
                {
                    FB.Init(InitCallback, OnHideUnity);
                }
                else
                {
                    FB.ActivateApp();
                }
            }
    
            //초기화되면 실행되는 콜백 함수. FB.ActivateApp()을 실행하는 것이 목적이다.
            protected virtual void InitCallback()
            {
                if (FB.IsInitialized)
                {
                    FB.ActivateApp();
                }
                else
                {
                    Debug.LogWarning("Failed to Initialize the Facebook SDK");
                }
            }
    
            
    
            // 일시정지 기능 (앱이 비활성화 되었을 경우)
            protected virtual void OnHideUnity(bool isGameShown)
            {
                if (!isGameShown)
                {
                    Time.timeScale = 0;
                }
                else
                {
                    Time.timeScale = 1;
                }
            }

     

     

    로그인 함수

            // 로그인 함수
            public void login()
            {
                // 읽기 권한으로 로그인한다.
                FB.LogInWithReadPermissions(permsRead, AuthCallback);
            }
    
            // 로그인 시 콜백받을 함수
            protected virtual void AuthCallback(ILoginResult result)
            {
                // 로그인 성공 시
                if (FB.IsLoggedIn)
                {
                    // 현재 AccessToken을 획득한다.
                    Facebook.Unity.AccessToken ac = Facebook.Unity.AccessToken.CurrentAccessToken;
    
                    // get userid from AccessToken
                    // 토큰에서 userId를 획득한다.
                    userId = ac.UserId;
    
                    // Debug용 로그 (넘어오는 permission들을 볼 수 있다.)
                    foreach (string obj in ac.Permissions)
                    {
                        Debug.Log("permission in AT :" + obj);
                    }
    
                    // 자동으로 유저 데이터 로딩을 할 건지 처리 (bool 변수)
                    if(AutoLoadProfileWhenLogIn)
                    {
                        // call the Api to get userInformations such as name, id, email
                        // id, name, email등을 얻기 위한 API 호출
                        FB.API(emailAPIUrl, HttpMethod.GET, getUserInfoCallback);
    
                        // call the Api to get public profile image
                        // 유저 이미지를 얻기 위한 API 호출
                        FB.API(pictureAPIUrl, HttpMethod.GET, getPictureCallback);
                    }
                }
            }
    
            protected virtual void getUserInfoCallback(IResult result)
            {
                
    
                if (result.Cancelled || !string.IsNullOrEmpty(result.Error))
                {
                    Debug.LogWarning("fail to read UserInfo");
                    return;
                }
                // Deserialize Json to Dictionary to get public user informations
                Dictionary<string, object> userInfo = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
    
                if (userInfo == null)
                {
                    Debug.LogError("Cannot parse user info. RawResult :" + result.RawResult);
                }
    
                if (userInfo["email"] != null && emailText != null)
                {
                    emailText.text = userInfo["email"].ToString();
                }
    
                if (userInfo["name"] != null && nameText != null)
                {
                    nameText.text = userInfo["name"].ToString();
                }
    
                if (userInfo["id"] != null && IdText != null)
                {
                    IdText.text = userInfo["id"].ToString();
                }
                
            }
    
            protected virtual void getPictureCallback(IGraphResult result)
            {
                if (result.Texture == null)
                {
                    Debug.LogWarning("Failed to get profile picture");
                    return;
                }
                this.profileTexture = result.Texture;
    
                if (this.ProfileImg == null)
                {
                    Debug.LogWarning("No Image to show profile");
                    return;        
                }
                this.ProfileImg.sprite = Sprite.Create(result.Texture, new Rect(0, 0, 128, 128), new Vector2());
                
            }



    별도의 권한 요청 없이 사용할 수 있는 기능은 여기까지인 것 같다.


     

    'Unity > Facebook' 카테고리의 다른 글

    FACEBOOK과 Unity - 01 환경설정하기  (1) 2020.06.09

    댓글

Designed by Tistory.