uniapp 微信小程序,保存图片到相册权限 拒绝后,无法再次调起授权

1、注意点
  • 背景:由于uni.authorize()方法,如果用户之前拒绝了授权,此接口会直接进入失败回调,需要搭配uni.getSettinguni.openSetting使用
  • 实现:通过 uni.getSetting() 获取用户授权信息,判断如同意授权/已授权,下载图片;如未授权,使用 uni.openSetting() 调起权限设置
  • 踩坑:微信公众平台提交正式版审核时,记得勾选采集用户隐私并进行相应信息完善,否则影响正式版设置权限
    -在这里插入图片描述
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();
          }
        });
      }
    }
  });
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值