根据不固定公网IP获取当前城市实时天气
获取本机公网IP
根据公网IP查找城市
通过获取城市解析天气
IEnumerator GetIP()
{
UnityWebRequest wwwWebIp = UnityWebRequest.Get(@"http://icanhazip.com/");
yield return wwwWebIp.SendWebRequest();
if (wwwWebIp.isNetworkError || wwwWebIp.isHttpError)
{
yield break;
}
else
{
// Debug.Log(wwwWebIp.downloadHandler.text);
}
string urlWeather = "https://api.seniverse.com/v3/location/search.json?key=SF0kp6pydMUKGZcEr&q=" + wwwWebIp.downloadHandler.text;//根据IP找城市
UnityWebRequest wwwQueryCity = UnityWebRequest.Get(urlWeather);
yield return wwwQueryCity.SendWebRequest();
if (wwwQueryCity.isNetworkError)
{
yield break;
}
else
{
// Debug.Log(wwwQueryCity.downloadHandler.text);
}
JObject cityData = JsonConvert.DeserializeObject<JObject>(wwwQueryCity.downloadHandler.text);
string cityId = cityData["results"][0]["id"].ToString();
city = cityData["results"][0]["name"].ToString();
string[] arry = cityData["results"][0]["path"].ToString().Split(',');
province = arry[2];
string urlWeathers = "https://api.seniverse.com/v3/weather/now.json?key=SF0kp6pydMUKGZcEr&location=" + cityId + "&language=zh-Hans&unit=c";//根据城市找天气
UnityWebRequest wwwWeather = UnityWebRequest.Get(urlWeathers);
yield return wwwWeather.SendWebRequest();
if (wwwWeather.isNetworkError)
{
yield break;
}
else
{
Debug.Log(wwwWeather.downloadHandler.text);
}
//解析天气
try
{
JObject weatherData = JsonConvert.DeserializeObject<JObject>(wwwWeather.downloadHandler.text);
string spriteName = string.Format("Weather/{0}@2x", weatherData["results"][0]["now"]["code"].ToString());
//天气文字
//Debug.Log(weatherData["results"][0]["now"]["text"].ToString()); //天气
//Debug.Log(weatherData["results"][0]["now"]["temperature"].ToString()); //温度
}
catch (System.Exception ex)
{
Debug.Log(ex.Message);
}
}
#注意事项
string urlWeather = “https://api.seniverse.com/v3/location/search.json?key=SF0kp6pydMUKGZcEr&q=” + wwwWebIp.downloadHandler.text;
当前key值需要注册https://www.seniverse.com/ 控制台——产品管理——添加产品——获取公钥或者私钥 当前免费版本