1、注意点
- 背景:由于uni.authorize()方法,如果用户之前拒绝了授权,此接口会直接进入失败回调,需要搭配
uni.getSetting
和uni.openSetting
使用 - 实现:通过 uni.getSetting() 获取用户授权信息,判断如同意授权/已授权,下载图片;如未授权,使用 uni.openSetting() 调起权限设置
- 踩坑:微信公众平台提交正式版审核时,记得勾选采集用户隐私并进行相应信息完善,否则影响正式版设置权限
-![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/518556de6bc14865ba43de04c87a6bbc.png#pic_center)
2、实现代码
const uploadPicture = () => {
uni.getSetting({
success: (res) => {
if (!res.authSetting[`scope.writePhotosAlbum`]) {
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
saveImage(state.poster);
},
fail: () => {
showAuthFailModal();
}
});
} else {
saveImage(state.poster);
}
}
});
};
const saveImage = (url: any) => {
uni.downloadFile({
url: url,
success: (res) => {
console.log(res);
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
});
},
fail: () => {
uni.showToast({
title: '保存失败',
icon: 'none'
});
}
});
},
fail: () => {
uni.showToast({
title: '下载失败',
icon: 'none'
});
}
});
};
const showAuthFailModal = () => {
uni.showModal({
title: '授权失败',
content: '请前往设置页手动授权该权限',
showCancel: false,
confirmText: '去设置',
success: (res) => {
if (res.confirm) {
uni.openSetting({
success: () => {
uni.hideLoading();
}
});
}
}
});
};