· 6 years ago · Nov 23, 2019, 07:16 AM
1using System.Collections;
2using System.Collections.Generic;
3using UnityEngine;
4using UnityEngine.Networking;
5using System;
6
7public class WeatherAPI : MonoBehaviour
8{
9 private string[] clima;
10
11 private string lat = "35";
12 private string lon = "139";
13
14 //OpenWeatherMap
15 private string apiKeyOpen = "73fe20ef57b05534cc5d787d6a8959e7";
16 private string urlOpen = "http://api.openweathermap.org/data/2.5/weather?lat=";
17 //API Key: 73fe20ef57b05534cc5d787d6a8959e7
18
19 public string[] RetornaClima(Action<string[]> callback)
20 {
21 Debug.Log("Funcao RetornaClima()");
22 clima = new string[2];
23 StartCoroutine(PuxaClima(callback));
24 Debug.Log("Ainda tem? " + clima[0]);
25 return clima;
26 }
27
28 public IEnumerator PuxaClima(Action<string[]> callback)
29 {
30 urlOpen = urlOpen + lat + "&lon=" + lon + "&APPID=" + apiKeyOpen;
31
32 UnityWebRequest request = UnityWebRequest.Get(urlOpen);
33 yield return request.SendWebRequest();
34 if (request.error == null || request.error == "")
35 {
36 string jsonString = request.downloadHandler.text;
37 //Debug.Log("Resposta: " + jsonString);
38 WeatherRaiz weather = setWeatherAttributes(jsonString);
39 clima[0] = weather.weather[0].icon;
40 clima[1] = weather.weather[0].main;
41 callback(clima);
42 Debug.Log("PuxaClima() icone " + clima[0]);
43 }
44 else
45 {
46 Debug.Log("Error: " + request.error);
47 callback(null);
48 //Outra API?
49 }
50 }
51
52 private WeatherRaiz setWeatherAttributes(string jsonString)
53 {
54 WeatherRaiz weatherJson = JsonUtility.FromJson<WeatherRaiz>(jsonString);
55 //Debug.Log(weatherJson.coord.lat);
56 //Debug.Log(weatherJson.weather[0].icon);
57 return weatherJson;
58 }
59}