본문 바로가기

Unity/뒤끝

[뒤끝 파헤치기] #07. 공지사항 받아오기

반응형

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

목록 바로가기

https://cheolmini.tistory.com/53

 

[뒤끝 파헤치기] #07. 공지사항 받아오기

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

 

동기, 비동기식으로 공지사항을 받아올 것 입니다.

 

공지사항은 임시 공지와 다르게 로그인을 해야지만 받아올 수 있습니다.


1. 뒤끝 콘솔에서 설정하기

뒤끝 콘솔 - 운영관리 - 공지사항 등록

 

 

게시 일시를 수정할 수 있으며 제목과 내용을 기입하여 줍니다.

 

 

이미지와 버튼 및 URL은 필수사항이 아닙니다.

 

이미지를 첨부할 시 공지사항에 이미지를 가져올수 있으며

 

버튼이름과 URL을 기입할 시 해당 링크로 이동시킬 수 있습니다.

 

 

2. 전역변수(이전 강의에 이어서 작성)

    [Header("Game Manager")]
    public Transform tempNotice;
    public Transform Notice;
    string linkURL;

 

3. 공지사항 이미지 받아오는 코루틴 함수

// 다른 블로그의 함수를 가져 왔습니다.
// 출처 : https://mrbinggrae.tistory.com/195?category=841356

   IEnumerator WWWImageDown(string url)
    {
        UnityWebRequest wr = new UnityWebRequest(url);
        DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
        wr.downloadHandler = texDl;
        yield return wr.SendWebRequest();

        if (!(wr.isNetworkError || wr.isHttpError))
        {
            if (texDl.texture != null)
            {
                print("이미지 로드 완료");
                Texture2D t = texDl.texture;
                Sprite s = Sprite.Create(t, new Rect(0, 0, t.width, t.height), Vector2.zero);
                Notice.GetChild(4).GetComponent<Image>().sprite = s;
            }
        }
        else
        {
            print("이미지가 없습니다.");
        }

        Notice.gameObject.SetActive(true);
    }
    


동기 방식


1. 공지사항 받아오기

 

Backend.Notice.NoticeList();

 

공지사항을 요청하면 JSON 형태로 받아옵니다.

 

유저 정보때의 강의와는 조금 다른 형태입니다. 

 

JSON 파일을 보시면 바로 알수 있습니다. rows 안 요소에 또다른 요소안에 값이 있습니다.

 

{
    rows:
    [ 
        { 
            content: // 공지 내용
                { S : "2019년 1월 31일 게임 업데이트 예정입니다. 업데이트 내용은 다음과 같습니다. " },
            postingDate: // 공지 게시 일자
                { S : "2018-12-19T09:30:00.000Z" },
            imageKey: // 첨부한 이미지 url 
                { S : "/upload/2147483648/notice/2018-12-27T02:55:36.845Z511886972.jpg" },
            inDate: // 공지 indate
                { S : "2018-12-19T09:26:53.382Z" },
            uuid: // 공지 uuid
                { S : "38b07660-0370-11e9-8d1d-7571a0570adf" },
            linkUrl: // 외부 링크 버튼 url
                { S : "http://thebackend.io" },
            isPublic: // 공개/비공개 여부
                { S : "y" },
            linkButtonName: // 외부 링크 버튼 이름
                { S : "buttonN" },
            author: // 작성자
                { S : "jake" },
            title: // 공지 제목
                { S : "게임 업데이트 공지" }
        },
        { 
            content: [Object],
            postingDate: [Object],
            imageKey: [Object],
            inDate: [Object],
            uuid: [Object],
            linkUrl: [Object],
            isPublic: [Object],
            linkButtonName: [Object],
            author: [Object],
            title: [Object] 
        } 
    ],
    // 불러온 데이터 이후의 데이터가 존재하는 경우 리턴됨
    // 불러온 데이터 이후의 데이터가 존재하지 않는 경우 리턴되지 않음
    LastEvaluatedKey:{
        gamer_id: { S: "notice" },
        inDate:{ S: "2019-08-19T06:45:07.816Z" },
        partition:{ S: "notice" }
    }
}

 

아래와 같이 새로운 형태로 가공하여 줍니다.

 

    public void getNotice()
    {
        BackendReturnObject BRO = Backend.Notice.NoticeList();

        if (BRO.IsSuccess())
        {

            JsonData noticeData = BRO.GetReturnValuetoJSON()["rows"][0];

            string date = noticeData["postingDate"][0].ToString();
            string title = noticeData["title"][0].ToString();
            string content = noticeData["content"][0].ToString().Substring(0, 10);
            string imgURL = "http://upload-console.thebackend.io" + noticeData["imageKey"][0];
            linkURL = noticeData["linkUrl"][0].ToString();

            Notice.GetChild(6).GetComponent<Text>().text = date;
            Notice.GetChild(5).GetComponent<Text>().text = title;
            Notice.GetChild(7).GetComponent<Text>().text = content;
            StartCoroutine(WWWImageDown(imgURL));

        }
    }


비동기 방식


1. 공지사항 받아오기

 

BackendAsyncClass.BackendAsync(Backend.Notice.NoticeList, ( callback ) => { // 이후 처리 });

 

   public void getNoticeAsync()
    {
        BackendAsyncClass.BackendAsync(Backend.Notice.NoticeList, (callback) =>
        {
            if (callback.IsSuccess())
            {
                JsonData noticeData = callback.GetReturnValuetoJSON()["rows"][0];

                string date = noticeData["postingDate"][0].ToString();
                string title = noticeData["title"][0].ToString();
                string content = noticeData["content"][0].ToString().Substring(0, 10);
                string imgURL = "http://upload-console.thebackend.io" + noticeData["imageKey"][0];
                linkURL = noticeData["linkUrl"][0].ToString();               

                Notice.GetChild(6).GetComponent<Text>().text = date;
                Notice.GetChild(5).GetComponent<Text>().text = title;
                Notice.GetChild(7).GetComponent<Text>().text = content;
                
                StartCoroutine(WWWImageDown(imgURL));                
            }
        });
    }

UI 구성하기


결과

로그인을 하지 않고 불러올시 에러가 발생하는 현상을 볼수 있습니다.

 

동기 방식 공지사항 받아오기
비동기 방식 공지사항 받아오기


참고 글

https://developer.thebackend.io/unity3d/guide/notice/noticev1_1/

 

뒤끝 개발자

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

developer.thebackend.io


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

 

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

읽어 주셔서 감사합니다.

 

더보기

검색어

뒤끝베이스

뒤끝강좌

뒤끝

뒤끝매치

뒤끝챗

유니티뒤끝

백앤드

유니티백앤드

유니티서버

유니티데이터저장

뒤끝기초

뒤끝서버

반응형