概要
HarmonyOS NEXT是华为公司自研的操作系统,好奇心促使我了解到其”一套代码工程,一次开发上架,多端按需部署,为用户呈现多设备统一且卓越的使用体验。“这不就跟uinapp类似吗,于是决定上手试试。
整体架构流程
开发工具:
DevEco Studio
开发框架:ArsTs
实现功能:下载并保存网络图片到手机上
技术细节
1、新建视图
build() {
Navigation() {
Image(this.imageUrl)
.margin({bottom:10})
.height(400)
.width('100%')
SaveButton({icon:SaveIconStyle.FULL_FILLED,text:SaveDescription.SAVE}).padding({
top: 12,
bottom: 12,
left: 24,
right: 24
})
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.theme'))
.title('预览')
.titleMode(NavigationTitleMode.Mini)
}
效果如图:
2、保存图片逻辑代码:
SaveButton({icon:SaveIconStyle.FULL_FILLED,text:SaveDescription.SAVE}).padding({
top: 12,
bottom: 12,
left: 24,
right: 24
}).onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
http.createHttp().request(
this.imageUrl,
{ expectDataType: http.HttpDataType.ARRAY_BUFFER }
).then(async (res) => {
this.imageBuffer = res.result as ArrayBuffer
const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
let helper = photoAccessHelper.getPhotoAccessHelper(context);
try {
// onClick触发后5秒内通过createAsset接口创建图片文件,5秒后createAsset权限收回。
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
// 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
await fs.write(file.fd, this.imageBuffer);
await fs.close(file.fd);
promptAction.showToast({
message: '图片已保存至相册',
duration: 2000
});
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
}
}).catch((err: BusinessError) => {
console.error(`Response err: Code is ${err.code}, message is ${JSON.stringify(err)}`);
promptAction.showToast({
message: '加载失败!',
duration: 2000
});
});
} else {
promptAction.showToast({
message: '设置权限失败!',
duration: 2000
});
}
})
至此这个功能就完成了
小结
需要注意的是:
1)网络图片需要使用http请求
2)配置相关权限等
1)一个是module.json配置
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
},
{
"name": "ohos.permission.GET_NETWORK_INFO"
}
]
2)华为后台配置服务器域名:
- 登录AppGallery Connect,点击“我的项目”。
- 在项目列表中点击您的项目,然后在页面顶端选择需配置服务器域名的元服务名称。
- 在左侧导航栏选择“开发管理 > 域名配置 > 服务器域名”,进入服务器域名配置主界面。
- 当前支持配置httpRequest、webSocket、download、upload四种服务器类型的域名,点击“修改”。
具体文档见华为的文档中心
该配置也适用于其他功能运行时报错”It is not allowed to access this domain.“2300998 不允许访问域名
至此这个功能就算完整完成了,打包等其他的,过后再写出来整理给大家,希望能帮到看文章的有缘人