【木棉花】在HarmonyOS中实现天气服务功能 原创 精华

木棉花_小蓝
发布于 2023-10-26 20:50
浏览
2收藏

介绍

本案例通过调用云端的天气服务API,在HarmonyOS中实现天气服务功能。开发者们可根据不同业务场景,在本案例的基础上集成自己的天气服务管理者模块。



【木棉花】在HarmonyOS中实现天气服务功能-鸿蒙开发者社区

开发环境要求

DevEco Studio版本:DevEco Studio 3.1 Release

● HarmonyOS SDK版本:API version 9

工程要求

● API9

Stage模型

【木棉花】在HarmonyOS中实现天气服务功能-鸿蒙开发者社区


正文

前置条件

在本案例中,实现天气服务的功能需要聚合数据平台提供的天气预报云服务。开发者需要在聚合数据平台注册和登录账号,然后申请天气预报的API,并通过实名认证获取自己的Key。通过Key,我们就可以通过http数据请求的方式调用天气预报的API,而官方会为每名开发者提供50次的每日免费调用次数。


代码结构

entry/src/main
  ├─ module.json5    		//模块的配置文件
  ├─ resources        		//资源文件集
  └─ ets
     ├─ XL_Modules      
     │  └─ XL_WeatherServiceManager.ts       //天气服务管理者ts模块
     ├─ pages
     │  └─ Index.ets			//主页面
     └─ entryability
          └─ EntryAbility.ts     //UIAbility类


关键代码

XL_WeatherServiceManager.ts

//导入http模块
import http from '@ohos.net.http'

//定义日志标签
const TAG1 = '------[XL_WeatherServiceManager  inquire] '

//提供云服务接口的网址片段
const Weather_Url_Part:string = "http://apis.juhe.cn/simpleWeather/query?key="

//开发者在聚合数据的请求Key(需要自行填入)
const key:string = ......

//声明一个专用于记录天气信息的数据类型
declare type RealTime_Weather_Result = {

  //实时数据
  realtime: any,

  //今日整体数据
  today:any,

  //是否成功拉取
  isFinished: boolean

}

/*
  异步函数: 获取对应城市的天气数据
 */
async function Pull_Weather_Data(cityName: string, Tag: string):Promise<RealTime_Weather_Result>{
	
  //预定义输出
  var output = {
    realtime: null,
    today: null,
    isFinished: false
  }

  //实例化一个http请求任务类
  let httpRequest = http.createHttp();

	//拼接url,以供访问服务器
  let URL = Weather_Url_Part+key+'&city='+cityName

  //调用异步方法request
  await httpRequest.request(
    URL,
    {
      //设置请求方法的类型
      method: http.RequestMethod.GET,
    }).then((data) => {

    //提取http响应的关键内容
    let Weather_Info = JSON.parse(data.result.toString())
	
    //当关键内容中所携带的错误码为0时,表示成功拉取了天气数据
    if(Weather_Info?.error_code == 0){

      console.info(TAG1+'Succeed! Obtain the weather data')
      
      //在日志栏打印天气信息
      console.info(TAG1+JSON.stringify(Weather_Info?.result?.realtime))
      console.info(TAG1+JSON.stringify(Weather_Info?.result?.future[0]))
			
      //存取天气信息
      output.realtime = Weather_Info?.result?.realtime
      output.today = Weather_Info?.result?.future[0]
      
      output.isFinished = true

    }else{
      console.error(Tag+Weather_Info?.reason)
    }

  }).catch(err => console.error(Tag + 'Http request failed, err:  ' + `${err}`))

  //销毁http任务类
  httpRequest.destroy()

	//输出
  return output

}


//默认导出的静态型模块类
class XL_WeatherServiceManager {

  //查询某城市天气的方法
  public static async inquire(cityName: string):Promise<RealTime_Weather_Result>{
    return await Pull_Weather_Data(cityName, TAG1)
  }
	
  /*
   *  敬请期待
   */
  
}

export default XL_WeatherServiceManager

在XL_WeatherServiceManager.ts中,我们通过http请求的方式,获取并解析服务器所回馈的天气预报信息。值得一提的是,我们创建了类XL_WeatherServiceManager,此类有个静态公共方法inquire调用了拉取天气信息的异步函数,并且XL_WeatherServiceManager是默认导出的。因此,我们可以在页面中导入XL_WeatherServiceManager,并通过执行require方法调用获取天气信息的功能。

import XL_WeatherServiceManager from  'ets/XL_Modules/XL_WeatherServiceManager'

......
let result = await XL_WeatherServiceManager.inquire('北京')
......


在页面中调用

Index.ets(伪代码)

//导入自定义的天气服务管理模块
import XL_WeatherServiceManager from  'ets/XL_Modules/XL_WeatherServiceManager'

@Entry
@Component
struct Index {

  @State message: string = 'Hello World'

  @State cityName:string = ''
  @State currentTemperature:string = ''
  @State currentWeather:string = ''
  @State todayTemperature:string = ''
  @State translateY:number = 700

  build() {

 				......
				
        Search({
          placeholder: '请输入城市名'
        })
        //添加回调函数
          .onSubmit((cityName:string)=>{
            this.Search(cityName)
          })
          ......
          
				......
       
    }

	//自定义异步方法
  async Search(cityName:string){
		
    //通过天气服务管理者调用inquire方法,并传入城市名参数
    let res = await XL_WeatherServiceManager.inquire(cityName)

    if(res.isFinished){
    
    	//根据需求读取信息
      this.currentTemperature = res.realtime.temperature
      this.currentWeather = res.realtime.info
      this.todayTemperature = res.today.temperature
      
      this.cityName = cityName
      this.translateY = 0
      
    }

  }


}


结尾

文章所述仅代表个人理解,如有不足恳请读者不吝赐教。

【木棉花】在HarmonyOS中实现天气服务功能-鸿蒙开发者社区


©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2023-10-26 20:50:44修改
4
收藏 2
回复
举报
5条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

感觉作者作品中小蓝的主题都设计的很不错

回复
2023-10-27 10:13:02
wzhishun
wzhishun

动画看起来非常流畅

已于2023-10-27 16:06:45修改
回复
2023-10-27 11:41:59
笨笨的婧婧
笨笨的婧婧

其实挺好奇数据平台的数据是从哪里弄的

回复
2023-10-27 16:22:33
木棉花_小蓝
木棉花_小蓝 回复了 笨笨的婧婧
其实挺好奇数据平台的数据是从哪里弄的

数据聚合平台通常都有它们自己的数据供应商,像天气数据,有可能来自国家气象局,也有可能来自其他与平台有合作的渠道商

回复
2023-10-27 16:35:35
晒太阳的懒猫
晒太阳的懒猫

先留个脚印,以后学习鸿蒙时看。谢谢楼主!

回复
2023-10-28 22:04:47
回复
    相关推荐