uni-app开发微信小程序如何授权(兼容iso和Android)保存图片到相册?

在使用uni-app官方api保存图片的时候,可能会因为没有授权导致失败,如何通过层层递进的方式,把授权代码写的优雅又实用呢?

  • 先贴一个调用示例:
this.saveImage('https://profile.csdnimg.cn/2/E/E/3_liuxin00020') // 简单调用
this.saveImage('https://profile.csdnimg.cn/2/E/E/3_liuxin00020', "是否允许获取保存相册权限", '暂无图片',"已保存到本地相册,请打开相册扫描") // 全参调用
  • 以下直接贴出个人写的一个公共方法,里面的文案请按需更改。最好把方法放在util里面使用,这样就可以到处调用啦。
/**
 * @description 保存图片,保存到系统相册
 * @param {String}  imgSrc 图片路径 
 * @param {String}  content 授权提示语句 
 * @param {String}  failTip 无图片保存时失败提示 
 * @param {String}  successTip 保存成功提示
 */
saveImage(imgSrc, content="是否允许获取保存相册权限", failTip='暂无图片', successTip="已保存到本地相册,请打开相册扫描") {
	uni.saveImageToPhotosAlbum({
		filePath: imgSrc,
		// 保存成功,直接给出提示
		success: (res) => {
			uni.showModal({
				title: '提示',
				content: successTip,
				showCancel: false,
				confirmText: "好的"
			})
		},

		// 保存失败,判断是否授权,未授权则调用授权,否则弹出失败信息
		fail(err) {
			console.error(err);
			if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg ===
				"saveImageToPhotosAlbum:fail authorize no response" || err.errMsg === "saveImageToPhotosAlbum:fail auth denied") { // 没有授权,重新授权,兼容iso和Android
				uni.showModal({
					title: '授权提示',
					content: content,
					success: (res) => {
						if (res.confirm) { // 点击确定,则调用相册授权
							uni.openSetting({
								success(settingdata) {
									if (settingdata.authSetting["scope.writePhotosAlbum"]) {
										console.log("获取权限成功,再次点击图片保存到相册")
										uni.showToast({
											title: '授权成功,请重试哦~'
										});
									} else {
										console.log("获取权限失败")
										uni.showToast({
											title: '请确定已打开保存权限',
											icon: "none"
										});
									}
								}
							})
						}
					}
				})
			} else if (err.errMsg === "saveImageToPhotosAlbum:fail file not found" || err.errMsg ===
				"saveImageToPhotosAlbum:fail file not exists" || err.errMsg ===
				"saveImageToPhotosAlbum:fail get file data fail"
			) { // 无图片,则提示
				uni.showToast({
					title: failTip,
					icon: "none"
				});
			}
		}
	})
},

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值