2021.05.13 네이버 블로그에 게시한 글을 이전한 게시글입니다.

 


 

날씨 API 정보를 받아와 UNITY에서 사용하도록 한다.

날씨 API는 OpenWeather에서 제공해주는 API를 사용하였다.

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 


1. API 설정

OpenWeather의 API를 사용하기 위해서는 API용 ID가 필요하다.

API id를 얻는 방법은 아래와 같다.

 

 

우선 가입을 한 후,

[API]탭에 들어가면 사용가능한 API들을 볼 수 있다.

현재 날씨의 정보가 필요하므로 Current Weather Data로 선택하였다.

 

 

사용하는 범위에 맞게 요금제를 선택할 수 있다.

 

구독한 후, MyApikey 페이지에서 확인하면 API key를 확인할 수 있다.

 


 

+ API 확인

현재 날씨의 API 주소는 아래와 같다.

(공식 사이트의 doc에서 확인가능하다)

 

서울의 현재 날씨를 나타내는 API 주소이다.

appid= 뒤에 본인의 API id를 입력하면 현재 날씨 정보를 얻을 수 있다.

 

 


2. API 취득 소스코드 작성

 

UnityWebRequest.Get(API_ADDRESS);
webRequest.SendWebRequest();

 

UnityWebRequest를 이용하여 네트워크로부터 정보를 얻어오는 코드이다.

 

json데이터 중, base는 변수명으로 사용할 수 없으므로 변수명을 바꿔서 사용해준다.

 


 

 

네트워크로부터 API를 받아오는 동안 프로그램이 대기하지않도록 코루틴으로 작성하여 대기를 줄여준다.

 

 

 


2. 소스코드

 

[WeatherController.cs]

 

using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;


public class WeatherController : MonoBehaviour
{
    //API 주소
    //===============================================
    public const string API_ADDRESS = @"api.openweathermap.org/data/2.5/weather?q=Seoul&appid=e";
    //===============================================

    //날씨 데이터가 다운로드되면 CallBack으로 필요한 함수로 돌아간다
    public delegate void WeatherDataCallback(WeatherData weatherData);

    //다운로드된 날씨 데이터. 중복 다운로드를 막기위하여 저장해둔다
    private WeatherData _weatherData;

    /// <summary>
    /// API로부터 날씨 데이터를 받아온다
    /// </summary>
    public void GetWeather(WeatherDataCallback callback)
    {
        //현재의 날씨 데이터가 없다면 API로부터 받아온다
        if (_weatherData == null)
        {
            StartCoroutine(CoGetWeather(callback));
        }
        else
        {
            //현재의 날씨 데이터가 존재한다면 그 날씨데이터를 그대로 사용한다
            callback(_weatherData);
        }
    }
    
    /// <summary>
    /// 날씨 API로부터 정보를 받아온다
    /// </summary>
    /// <param name="callback"></param>
    /// <returns></returns>
    private IEnumerator CoGetWeather(WeatherDataCallback callback)
    {
        Debug.Log("날씨 정보를 다운로드합니다");

        var webRequest = UnityWebRequest.Get(API_ADDRESS);
        yield return webRequest.SendWebRequest();

        //만약 에러가 있을 경우
        if(webRequest.isHttpError || webRequest.isNetworkError)
        {
            Debug.Log(webRequest.error);
            yield break;
        }

        //다운로드 완료
        var downloadedTxt = webRequest.downloadHandler.text;

        Debug.Log("날씨 정보가 다운로드 되었습니다! : " + downloadedTxt);

        //유니티 언어와 겹치므로 base를 사용할 수 없기때문에 Replace가 필요하다
        string weatherStr = downloadedTxt.Replace("base", "station");

        _weatherData = JsonUtility.FromJson<WeatherData>(weatherStr);
        callback(_weatherData);
    }
}

 

[WeatherData.cs] - json파싱용 클라스

 

using System;

[Serializable]
public class WeatherData
{
    public Coord coord;
    public Weather[] weather;
    public string station;
    public Main main;
    public int visibility;
    public Wind wind;
    public Clouds clouds;
    public int dt;
    public Sys sys;
    public int id;
    public string name;
    public int cod;
}

[Serializable]
public class Coord
{
    public float lon;
    public float lat;
}

[Serializable]
public class Weather
{
    public int id;
    public string main;
    public string description;
    public string icon;
}

[Serializable]
public class Wind
{
    public float speed;
    public float deg;
}

[Serializable]
public class Main
{
    public float temp;
    public int pressure;
    public int humidity;
    public float temp_min;
    public float temp_max;
}

[Serializable]
public class Clouds
{
    public int all;
}

[Serializable]
public class Sys
{
    public int type;
    public int id;
    public float message;
    public string country;
    public int sunrise;
    public int sunset;
}

+ Recent posts