获取实时天气这里用到的是【心知天气】开发接口,再用Newtonsoft.Json解析返回的数据。主要为三步
1.查询本机网络的公网IP(http://icanhazip.com/)
2.根据公网IP查询所在城市。
3.根据所在城市查询天气。
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class CityWeather : MonoBehaviour
{
public Text textWeather;
public Image imgWeather;
public Text textTemperature;
public Text textCity;
void Start()
{
StartCoroutine(GetRuntimeWeather());
}
IEnumerator GetRuntimeWeather()
{
//获取本地公网IP
UnityWebRequest wwwWebIp = UnityWebRequest.Get(@"http://icanhazip.com/");
yield return wwwWebIp.SendWebRequest();
if (wwwWebIp.isNetworkError || wwwWebIp.isHttpError)
{
yield break;
}
//根据IP查询城市(心知天气提供接口,需要申请key)
string urlQueryCity = "https://api.seniverse.com/v3/location/search.json?key={yourkey}&q=" + wwwWebIp.downloadHandler.text;
UnityWebRequest wwwQueryCity = UnityWebRequest.Get(urlQueryCity);
yield return wwwQueryCity.SendWebRequest();
if (wwwQueryCity.isNetworkError || wwwQueryCity.isHttpError)
{
yield break;
}
JObject cityData = JsonConvert.DeserializeObject(wwwQueryCity.downloadHandler.text);
string cityId = cityData["results"][0]["id"].ToString();
textCity.text = cityData["results"][0]["name"].ToString();
//根据城市查询天气(心知天气提供接口,需要申请key)
string urlWeather = string.Format("https://api.seniverse.com/v3/weather/now.json?key={yourkey}&location={0}&language=zh-Hans&unit=c", cityId);
UnityWebRequest wwwWeather = UnityWebRequest.Get(urlWeather);
yield return wwwWeather.SendWebRequest();
if (wwwWeather.isNetworkError || wwwWeather.isHttpError)
{
Debug.Log(wwwWeather.error);
}
//解析天气
try
{
JObject weatherData = JsonConvert.DeserializeObject(wwwWeather.downloadHandler.text);
string spriteName = string.Format("Weather/{0}@2x", weatherData["results"][0]["now"]["code"].ToString());
//天气文字
textWeather.text = weatherData["results"][0]["now"]["text"].ToString();
//图片,可以在心知天气上下载
imgWeather.sprite = Resources.Load(spriteName);
//温度
textTemperature.text = string.Format("{0} °C", weatherData["results"][0]["now"]["temperature"].ToString());
}
catch (System.Exception ex)
{
Debug.Log(ex.Message);
}
}
}
/*
* {
"results": [{
"location": {
"id": "WX4FBXXFKE4F",
"name": "北京",
"country": "CN",
"path": "北京,北京,中国",
"timezone": "Asia/Shanghai",
"timezone_offset": "+08:00"
},
"now": {
"text": "晴",
"code": "0",
"temperature": "-10"
},
"last_update": "2021-01-08T09:20:00+08:00"
}]
}
*/