Unity接入心知天气,获取当前城市天气状况

一、效果图 

二、注册心知天气

心知天气 - 登录

注册完成申请免费版API

 获取APIKey

文档地址:查看你的 API密钥 · 语雀 (yuque.com) 

图片下载地址:天气现象代码说明 | 心知天气文档 (seniverse.com) 

在unity新建Resources文件夹,将图片导入(因为代码会根据返回的图片名称在这个文件夹下查找图片,注意要把图片处理成精灵格式Sprite)

二、 代码实现

思路:

1.获取本地公网IP   http://icanhazip.com/

2.根据IP查询城市(心知天气提供接口,需要申请key)

https://api.seniverse.com/v3/location/search.json?key=私钥&q=城市

3.根据城市查询天气(心知天气提供接口,需要申请key)

https://api.seniverse.com/v3/weather/now.json?key=私钥&location={0}&language=zh-Hans&unit=c城市id

 json插件可以使用LitJson.dll或者Newtonsoft.Json,这里我用的是Newtonsoft.Json

下载地址: 提取码 syq1

LitJson.dll https://pan.baidu.com/share/init?surl=evpFU9FnL3KeP29_nVQlTQ

Newtonsoft.Json  https://pan.baidu.com/s/1fiRwL2qcepzgxOUwcTs1fQ

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
//using LitJson;

/// <summary>
/// 城市天气
/// </summary>
public class CityWeather : MonoBehaviour
{
    public Image imgWeather;    //天气图片
    public Text textWeather;    //天气
    public Text textTemperature;//温度
    public Text textCity;       //城市

    void Start()
    {
        StartCoroutine(GetRuntimeWeather());
    }

    IEnumerator GetRuntimeWeather()
    {
        //1.获取本地公网IP
        UnityWebRequest wwwWebIp = UnityWebRequest.Get(@"http://icanhazip.com/");
        yield return wwwWebIp.SendWebRequest();
        if (wwwWebIp.isNetworkError || wwwWebIp.isHttpError)
        {
            yield break;
        }

        //2.根据IP查询城市(心知天气提供接口,需要申请key)***这里别忘记修改
        string urlQueryCity = "https://api.seniverse.com/v3/location/search.json?key=私钥&q=" + wwwWebIp.downloadHandler.text;
        UnityWebRequest wwwQueryCity = UnityWebRequest.Get(urlQueryCity);
        yield return wwwQueryCity.SendWebRequest();
        if (wwwQueryCity.isNetworkError || wwwQueryCity.isHttpError)
        {
            yield break;
        }

        JObject cityData = JsonConvert.DeserializeObject<JObject>(wwwQueryCity.downloadHandler.text);
        string cityId = cityData["results"][0]["id"].ToString();
        textCity.text = cityData["results"][0]["name"].ToString(); //城市

        //3.根据城市查询天气(心知天气提供接口,需要申请key)***这里别忘记修改
        string urlWeather = string.Format("https://api.seniverse.com/v3/weather/now.json?key=私钥&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);
        }

        //4.解析天气
        try
        {
            JObject weatherData = JsonConvert.DeserializeObject<JObject>(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<Sprite>(spriteName);
            //Debug.Log(spriteName);

            //温度
            textTemperature.text = string.Format("{0} °C", weatherData["results"][0]["now"]["temperature"].ToString());
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
}


/*
 * 返回的Json天气格式
 * {
	"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"
	}]
}
 */

三、问题解决 

经过几个朋友的测试,如果在运行中 textWeather.text = weatherData["results"][0]["now"]["text"].ToString();这句话出现超出数组索引问题,大概率是第一步获取公网ip的原因,在网页中访问 http://icanhazip.com/这个地址,返回的是

(IPV6地址),而不是(IPV4地址)这种格式的地址的话,就会出错。
 

原因: 可能是你的路由器支持IPV6导致。

win+R 输入cmd 打开控制台应用窗口,输入ipconfig 查看,看看是否ipV6不存在(注意不是本地IPV6)

 不支持ipV6使用 http://icanhazip.com/这个地址是没问题的

解决办法:

更换获取公网ip

分享一些获取公网ip的url地址_IP大侠的博客-CSDN博客_外网url

 

  • 6
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值