본문 바로가기

Unity/뒤끝

[뒤끝 파헤치기] #14. 친구 기능

반응형

해당 강의는 PC환경에 최적화 된 글 입니다.

목록 바로가기

https://cheolmini.tistory.com/53

 

[뒤끝 파헤치기] #14. 친구 기능

뒤끝 파헤치기 두번째 강의글 입니다.

 

동기, 비동기식으로 친구를 요청, 추가, 삭제를 해볼 것 입니다.


1. 뒤끝 콘솔 설정

 

뒤끝 콘솔 - 소셜 관리 - 설정

 

해당 옵션을 설정해줘야 친구신청시 오류가 발생하지 않습니다.

 

 

 

 

2. 친구의 inDate 값 가져오기

 

친구를 요청하기 위해선 친구의 inDate 값이 필요합니다.

그렇기 떄문에 아래와 같은 함수를 작성합니다.

 

    string getGammerIndate(string nickname)
    {
        BackendReturnObject BRO = Backend.Social.GetGamerIndateByNickname(nickname);

        if (BRO.IsSuccess())
        {
            JsonData GamerIndate = BRO.GetReturnValuetoJSON()["rows"][0];

            string indate = GamerIndate["inDate"][0].ToString();

            return indate;
        }
        return null;
    }

 

3. 예외처리 함수

 

참고만 해주세요

 

    void Error(string errorCode, string type)
    {
        if (errorCode == "DuplicatedParameterException")
        {
            if (type == "UserFunc") print("중복된 사용자 아이디 입니다.");
            else if (type == "UserNickname") print("중복된 닉네임 입니다.");
            else if (type == "Friend") print("이미 요청되었거나 친구입니다.");
        }
        else if (errorCode == "BadUnauthorizedException")
        {
            if (type == "UserFunc") print("잘못된 사용자 아이디 혹은 비밀번호 입니다.");
        }
        else if (errorCode == "UndefinedParameterException")
        {
            if (type == "UserNickname") print("닉네임을 다시 입력해주세요");
        }
        else if (errorCode == "BadParameterException")
        {
            if (type == "UserNickname") print("닉네임 앞/뒤 공백이 있거나 20자 이상입니다.");
            else if (type == "UserPW") print("잘못된 이메일입니다.");
            else if (type == "gameData") print("잘못된 유형의 테이블 입니다.");
        }
        else if (errorCode == "NotFoundException")
        {
            if (type == "UserPW") print("등록된 이메일이 없습니다.");
            else if (type == "Coupon") print("중복 사용이거나 기간이 만료된 쿠폰입니다.");
            else if (type == "gameData") print("해당 테이블을 찾을 수 없습니다.");
        }
        else if (errorCode == "Too Many Request")
        {
            if (type == "UserPW") print("요청 횟수를 초과하였습니다. (1일 5회)");
        }
        else if (errorCode == "PreconditionFailed")
        {
            if (type == "gameData") print("해당 테이블은 비활성화 된 테이블 입니다.");
            else if (type == "Friend") print("받는 사람 혹은 보내는 사람의 요청갯수가 꽉 찬 상태입니다.");
        }
        else if (errorCode == "ServerErrorException")
        {
            if (type == "gameData") print("하나의 row이 400KB를 넘습니다");
        }
        else if (errorCode == "ForbiddenError")
        {
            if (type == "gameData") print("타인의 정보는 삭제가 불가능합니다.");
        }
    }


동기 방식


1. 친구 요청

 

Backend.Social.Friend.RequestFriend("gamerIndate");

 

위에서 작성한 함수를 통해 inDate값을 가져온 후 해당 값으로 친구를 요청합니다.

 

 public void requestFriend()
    {
        BackendReturnObject BRO = Backend.Social.Friend.RequestFriend(getGammerIndate(FriendNickname.text));

        if (BRO.IsSuccess()) print($"동기 방식 {FriendNickname.text}님에게 친구요청 성공");
        else Error(BRO.GetErrorCode(), "Friend");

        FriendNickname.text = "";
    }

 

2. 친구 요청을 받은 리스트

 

Backend.Social.Friend.GetReceivedRequestList();

 

친구 요청이 들어온 리스트를 받습니다.

 

이때 닉네임과 inDate 값을 저장합니다.

 

그후 스크롤 뷰에 출력합니다.

 

 public void getReceivedFriendList()
    {
        BackendReturnObject BRO = Backend.Social.Friend.GetReceivedRequestList();

        if (BRO.IsSuccess())
        {
            JsonData jsonData = BRO.GetReturnValuetoJSON()["rows"];

            for (int i = 0; i < jsonData.Count; i++)
            {
                JsonData Data = jsonData[i];

                string nickname = Data["nickname"][0].ToString();
                string inDate = Data["inDate"][0].ToString();

                for (int j = 0; j < ReceivedFriendList.childCount; j++)
                {
                    if (!ReceivedFriendList.GetChild(j).gameObject.activeSelf)
                    {
                        ReceivedFriendList.GetChild(j).GetChild(1).GetComponent<Text>().text = nickname;
                        ReceivedFriendList.GetChild(j).GetChild(2).GetComponent<Text>().text = inDate;
                        ReceivedFriendList.GetChild(j).gameObject.SetActive(true);
                        break;
                    }
                }
            }
            print("동기 방식 친구 요청 리스트 조회 성공");
        }
    }

 

3. 친구 수락

 

Backend.Social.Friend.AcceptFriend("gamerIndate");

 

친구 요청을 받을때 inDate 값을 저장했기때문에 해당 값을 넣어줍니다.

 

    public void AcceptFriend()
    {
        string inDate = EventSystem.current.currentSelectedGameObject.transform.parent.GetChild(2).GetComponent<Text>().text;

        BackendReturnObject BRO = Backend.Social.Friend.AcceptFriend(inDate);

        if (BRO.IsSuccess())
        {
            EventSystem.current.currentSelectedGameObject.transform.parent.gameObject.SetActive(false);
            print("동기 방식 친구 수락 완료");
        }
        else Error(BRO.GetErrorCode(), "Friend");
    }

 

4. 친구 거절

 

Backend.Social.Friend.RejectFriend("gamerIndate");

 

친구 요청을 받을때 inDate 값을 저장했기때문에 해당 값을 넣어줍니다.

 

    public void RejectFriend()
    {
        string inDate = EventSystem.current.currentSelectedGameObject.transform.parent.GetChild(2).GetComponent<Text>().text;

        BackendReturnObject BRO = Backend.Social.Friend.RejectFriend(inDate);

        if (BRO.IsSuccess())
        {
            EventSystem.current.currentSelectedGameObject.transform.parent.gameObject.SetActive(false);
            print("동기 방식 친구 거절 완료");
        }
    }

 

5. 친구 리스트

 

Backend.Social.Friend.GetFriendList();

 

친구 수락을 한 리스트를 조회합니다.

 

이때 닉네임과 inDate 값을 저장합니다.

 

그후 스크롤 뷰에 출력합니다.

 

    public void getFriendList()
    {
        BackendReturnObject BRO = Backend.Social.Friend.GetFriendList();

        if (BRO.IsSuccess())
        {
            JsonData jsonData = BRO.GetReturnValuetoJSON()["rows"];

            for (int i = 0; i < jsonData.Count; i++)
            {
                JsonData Data = jsonData[i];

                string nickname = Data["nickname"][0].ToString();
                string indate = Data["inDate"][0].ToString();

                for (int j = 0; j < FriendList.childCount; j++)
                {
                    if (!FriendList.GetChild(j).gameObject.activeSelf)
                    {
                        FriendList.GetChild(j).GetChild(1).GetComponent<Text>().text = nickname;
                        FriendList.GetChild(j).GetChild(2).GetComponent<Text>().text = indate;
                        FriendList.GetChild(j).gameObject.SetActive(true);
                        break;
                    }
                }
            }

            print("동기 방식 친구 리스트 조회 성공");
        }
    }

 

6. 친구 삭제

 

Backend.Social.Friend.BreakFriend("gamerIndate");

 

친구 수락을 한 리스트를 조회할때 얻은 inDate값을 넣어줍니다.

 

    public void BreakFriend()
    {
        string inDate = EventSystem.current.currentSelectedGameObject.transform.parent.GetChild(2).GetComponent<Text>().text;

        BackendReturnObject BRO = Backend.Social.Friend.BreakFriend(inDate);

        if (BRO.IsSuccess())
        {
            EventSystem.current.currentSelectedGameObject.transform.parent.gameObject.SetActive(false);
            print("동기 방식 친구 삭제 완료");
        }
    }

 



비동기 방식


1. 친구 요청

 

BackendAsyncClass.BackendAsync(Backend.Social.Friend.RequestFriend, "gamerIndate", (callback) => { // 이후 처리 });

 

    public void requestFriendAsync()
    {
        BackendAsyncClass.BackendAsync(Backend.Social.Friend.RequestFriend, getGammerIndate(FriendNickname.text), (callback) =>
        {
            if (callback.IsSuccess()) print($"비동기 방식 {FriendNickname.text}님에게 친구요청 성공");
            else Error(callback.GetErrorCode(), "Friend");

            FriendNickname.text = "";
        });
    }

 

2. 친구 요청을 받은 리스트

 

Backend.Social.Friend.GetReceivedRequestList((callback) => { // 이후 처리 });

 

public void getReceivedFriendListAsync()
    {
        BackendAsyncClass.BackendAsync(Backend.Social.Friend.GetReceivedRequestList, BRO =>
       {
           if (BRO.IsSuccess())
           {
               JsonData jsonData = BRO.GetReturnValuetoJSON()["rows"];

               for (int i = 0; i < jsonData.Count; i++)
               {
                   JsonData Data = jsonData[i];

                   string nickname = Data["nickname"][0].ToString();
                   string inDate = Data["inDate"][0].ToString();

                   for (int j = 0; j < ReceivedFriendList.childCount; j++)
                   {
                       if (!ReceivedFriendList.GetChild(j).gameObject.activeSelf)
                       {
                           ReceivedFriendList.GetChild(j).GetChild(1).GetComponent<Text>().text = nickname;
                           ReceivedFriendList.GetChild(j).GetChild(2).GetComponent<Text>().text = inDate;
                           ReceivedFriendList.GetChild(j).gameObject.SetActive(true);
                           break;
                       }
                   }
               }
               print("비동기 방식 친구 요청 리스트 조회 성공");
           }
       });
    }

 

3. 친구 수락

 

BackendAsyncClass.BackendAsync(Backend.Social.Friend.AcceptFriend, "gamerIndate", (callback) => { // 이후 처리 });

 

    public void AcceptFriendAsync()
    {
        string inDate = EventSystem.current.currentSelectedGameObject.transform.parent.GetChild(2).GetComponent<Text>().text;

        BackendAsyncClass.BackendAsync(Backend.Social.Friend.AcceptFriend, inDate, (callback) =>
        {
            if (callback.IsSuccess())
            {
                EventSystem.current.currentSelectedGameObject.transform.parent.gameObject.SetActive(false);
                print("비동기 방식 친구 수락 완료");
            }
            else Error(callback.GetErrorCode(), "Friend");
        });
    }

 

4. 친구 거절

 

BackendAsyncClass.BackendAsync(Backend.Social.Friend.RejectFriend, "gamerIndate", (callback) => { // 이후 처리 });

 

    public void RejectFriendAsync()
    {
        string inDate = EventSystem.current.currentSelectedGameObject.transform.parent.GetChild(2).GetComponent<Text>().text;

        BackendAsyncClass.BackendAsync(Backend.Social.Friend.RejectFriend, inDate, (callback) =>
        {
            if (callback.IsSuccess())
            {
                EventSystem.current.currentSelectedGameObject.transform.parent.gameObject.SetActive(false);
                print("비동기 방식 친구 거절 완료");
            }
        });
    }

 

5. 친구 리스트

 

BackendAsyncClass.BackendAsync(Backend.Social.Friend.GetFriendList, (callback) => { // 이후 처리 });

 

    public void getFriendListAsync()
    {
        BackendAsyncClass.BackendAsync(Backend.Social.Friend.GetFriendList, (callback) =>
        {
            if (callback.IsSuccess())
            {
                JsonData jsonData = callback.GetReturnValuetoJSON()["rows"];

                for (int i = 0; i < jsonData.Count; i++)
                {
                    JsonData Data = jsonData[i];

                    string nickname = Data["nickname"][0].ToString();
                    string indate = Data["inDate"][0].ToString();

                    for (int j = 0; j < FriendList.childCount; j++)
                    {
                        if (!FriendList.GetChild(j).gameObject.activeSelf)
                        {
                            FriendList.GetChild(j).GetChild(1).GetComponent<Text>().text = nickname;
                            FriendList.GetChild(j).GetChild(2).GetComponent<Text>().text = indate;
                            FriendList.GetChild(j).gameObject.SetActive(true);
                            break;
                        }
                    }
                }
                print("비동기 방식 친구 리스트 조회 성공");
            }
        });
    }

 

6. 친구 삭제

 

BackendAsyncClass.BackendAsync(Backend.Social.Friend.BreakFriend, "gamerIndate", (callback) => { // 이후 처리 });

 

    public void BreakFriendAsync()
    {
        string inDate = EventSystem.current.currentSelectedGameObject.transform.parent.GetChild(2).GetComponent<Text>().text;

        BackendAsyncClass.BackendAsync(Backend.Social.Friend.BreakFriend, inDate, (callback) =>
        {
            if (callback.IsSuccess())
            {
                EventSystem.current.currentSelectedGameObject.transform.parent.gameObject.SetActive(false);
                print("비동기 방식 친구 삭제 완료");
            }
        });
    }

 


UI 구성하기

스크롤 뷰를 통해 리스트를 구현하였습니다.

 

전역 변수는 아래와 같이 선언하였습니다.

    [Header("Social")]
    public InputField GamerNickname;
    public InputField FriendNickname;
    public Transform ReceivedFriendList;
    public Transform FriendList;

 

 


결과

 

친구 요청

 

친구 수락 및 친구 리스트 조회

 

친구 거절 및 친구 삭제


참고 글

 

https://developer.thebackend.io/unity3d/guide/social/friendv1_2/

 

뒤끝 개발자

모바일 게임 서버를 쉽게 생성, 관리 할 수 있는 뒤끝의 개발자 사이트입니다.

developer.thebackend.io

 

https://developer.thebackend.io/unity3d/guide/social/friend_requestv1_2/

 

뒤끝 개발자

모바일 게임 서버를 쉽게 생성, 관리 할 수 있는 뒤끝의 개발자 사이트입니다.

developer.thebackend.io


모든 프로젝트는 깃 허브에 업데이트 할 예정입니다.

 

https://github.com/CM-Games/BackEnd

읽어 주셔서 감사합니다.

 

더보기

검색어

뒤끝베이스

뒤끝강좌

뒤끝

뒤끝매치

뒤끝챗

유니티뒤끝

백앤드

유니티백앤드

유니티서버

유니티데이터저장

뒤끝기초

뒤끝서버

반응형