티스토리 뷰

반응형

[1] UntiyWebRequest

 

UnityWebRequest 는 web server와의 HTTP communication flow를 handle 해줍니다.

UnityWebRequest는 static utility functions 을 포함하고 있습니다. 

 

 

web request 를 보내려면 UnityWebRequest instance 의 UnityWebRequest.SendWebRequest 를 콜하면 됩니다. 

request 결과는 web request 의  result 프로퍼티, responseCode 프로퍼티, error 프로퍼티를 보고 파악할 수 있습니다. 

 

[2] Get 요청 해보기

url과 callback 함수를 받는 Get 함수를 만들어주면 됩니다. (이 글을 참고해줬어요)

Action을 사용하기 위해 System을 임포트 해줬고

UnityWebRequest를 사용하기 위해  UnityEngine.Networking 을 임포트해줬습니다. 

using UnityEngine;
using System.Collections;

using System;
using UnityEngine.Networking;

public class ApiManager : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        StartCoroutine(Get("https://~~~~~", (request) =>
        {
            if (request.result == UnityWebRequest.Result.Success && request.responseCode == 200)
            {
                Debug.Log(request.downloadHandler.text);
            }
            else
            {
                Debug.Log("[Error]:" + request.responseCode + request.error);
            }
        }));
    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator Get(string url, Action<UnityWebRequest> callback)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();
        callback(request);
    }
}

 

그리고 게임오브젝트 아무거나 스크립트를 붙여서 게임플레이를 해볼게요 (스크립트만 따로 돌리는 법을 몰라서..ㅠㅠ) 

request.downloadHandler.text 가 출력된 것을 보면 json string 을 담고 있는데요,

json을 핸들링하는 법을 아래에서 살펴보겠습니다. 

 

[3] JsonUtility

JsonUtility 의 FromJson 은 json representation에서 object를 만들어줍니다. 

문서의 예제를 보면 이해가 쉽습니다. 

using UnityEngine;

[System.Serializable]
public class PlayerInfo
{
    public string name;
    public int lives;
    public float health;

    public static PlayerInfo CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<PlayerInfo>(jsonString);
    }

    // Given JSON input:
    // {"name":"Dr Charles","lives":3,"health":0.8}
    // this example will return a PlayerInfo object with
    // name == "Dr Charles", lives == 3, and health == 0.8f.
}

 

이 메소드는 Unity serializer 를 사용하기 때문에 

class/struct 에다가 Serializable attribute 를 마킹해줘야한다고 합니다. 

 

자세한 것은 아래 문서 내용을 참고해주세요 

 

Internally, this method uses the Unity serializer; therefore the type you are creating must be supported by the
serializer. It must be a plain class/struct marked with the Serializable attribute. Fields of the object must have types supported by the serializer. Fields that have unsupported types, as well as private fields or fields marked with the NonSerialized attribute, will be ignored.

 

[4] 기록

저는 이런식으로 Api 메소드들을 추가하려고 합니다. 

-  C# 문서 > Structure types 보면 생성자에 소문자를 사용해주는 데 저는 Swift 인간이라.. 

언더스코어 해줬습니다. 

-  FromJson이 실패할 경우(서버의 필드명과 내가 정의한 모델의 필드명이 다르거나 할 때..) 
Object는 만들어지나 Object 안의 필드들이 Null 입니다.
즉 Json -> Object가 실패할 일이 없으므로 FromJson 에러헨들링은 따로 안해줘도 되는 것 같아요

using UnityEngine;
using System.Collections;

using System;
using UnityEngine.Networking;

public struct ApiError
{
    public long statusCode;
    public string message;

    public ApiError(long _statusCode, string _message)
    {
        statusCode = _statusCode;
        message = _message;
    }
}

public struct Api
{
    public IEnumerator GetBooks(Action<Book[]> onSuccess, Action<ApiError> onFailure)
    {
        string url = "https://~~~~~~";
        yield return Get(url, (request) =>
        {
            if (request.result == UnityWebRequest.Result.Success && request.responseCode == 200)
            {
                string jsonString = request.downloadHandler.text;
                var response = JsonUtility.FromJson<ApiResponse<ListResponse<Book>>>(jsonString);
                onSuccess(response.data.list);
            }
            else
            {
                onFailure(new ApiError(request.responseCode, request.error));
            }
        });
    }

    IEnumerator Get(string url, Action<UnityWebRequest> callback)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();
        callback(request);
    }
}

 

api를 사용하는 쪽에서 이런 식으로 코드가 나오게 됩니다!  

StartCoroutine(api.GetBooks(onSuccess: (books) =>
{
    // do something
}, onFailure: (error) =>
{
    // do something
}));

 

 

 

 

반응형
댓글