原生小程序
目录
通过wx.getSetting判断scope.writePhotosAbum的值:
若为true则已经授权,直接调用保存到相册的方法
若为undefined,则说明是第一次授授权框只在第一次询问时弹出(下图),如果用户已经拒绝了,则不会弹出
若为false,则已经拒绝了授权,这时候我们需要调用wx.openSetting引导用户打开设置,保存到相册,wx.openSettina设置界面只会出现小程序已经用户请求过的权限
话不多说,上代码:
// 保存图片方法
saveImage(filePath) {
wx.saveImageToPhotosAlbum({
filePath: "/images/component/backColor.png", // 此为图片路径
success: (res) => {
this.showToast('保存成功')
},
fail: (err) => {
console.log(err)
this.showToast('保存失败,请稍后重试')
}
})
},
// 微信提示方法
showToast(title) {
wx.showToast({
title: title
});
},
// 点击保存图片到相册(授权)
downloadClick() {
const _this=this
return new Promise((resolve, reject) => {
wx.getSetting({
success: (res) => {
console.log(111,res)
if (res.authSetting['scope.writePhotosAlbum'] == undefined) {
console.log(999,wx.authorize())
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
_this.saveImage()
},
fail() {
wx.showToast({
title: '您没有授权,无法保存到相册',
icon: 'none'
})
}
})
} else if (res.authSetting['scope.writePhotosAlbum'] == false) {
wx.showModal({
title: "授权失败",
content: "请开启授权",
success(resModal) {
if (resModal.confirm) {
wx.openSetting({
success: function (e) {
console.log("打开授权页面", e);
// false 表示打开设置面板,但是没有授权就返回了
if (e.authSetting['scope.writePhotosAlbum'] == false) {
console.log(222)
wx.showToast({
title: '您没有授权,无法保存到相册',
icon: 'none'
})
} else {
_this.saveImage()
resolve()
}
}
})
} else if (res.cancel) {
console.log("打开授权页面弹框-拒绝授权")
reject();
}
}
})
} else {
_this.saveImage()
resolve()
}
},
fail: (res) => {
console.log("授权失败", res);
reject();
}
})
})
}
})