美文网首页
微信小程序 如何在用户拒绝授权后重新授权

微信小程序 如何在用户拒绝授权后重新授权

作者: 阿昕_ | 来源:发表于2018-02-19 03:42 被阅读7738次

起源

  • 在做小程序时授权问题是少不了的,可有时候总有人会点击拒绝授权,那我们开发拿不到需要的数据是不是很苦恼呢?我在自己正在做的小程序里使用了一种方法,现在分享出来~~
  • 我的这个demo是个人信息+地理位置的双重授权

思路

  • 要么授权通过,进入首页
  • 要么拒绝授权,停留在有授权入口的页面
  • 需要设置一个标志值:authorizeInfo,根据此值得真假来决定是渲染首页还是渲染显示重新授权的页面。

过程

在页面显示的时候,获取用户信息与地理位置(当然,这是我所需要的)

// userInfo
    wx.getUserInfo({
      success:res=>{
        this.setData({userInfo : true})
      },
      fail:res=>{
        this.setData({ userInfo: false })
      }
    })
    // locationInfo
    wx.getLocation({
      success: res => {
        this.setData({ locationInfo: true })
      },
      fail: res => {
        this.setData({ locationInfo: false })
      }
    })

authorizeInfo的设置就要依靠刚刚获取的这两个值了,设置定时器不断执行authorizeInfo,直到userInfolocationInfo两个值都为true就把定时器清除(设置定时器是因为刚开始获取userInfolocationInfo可能会失败),当两者都为真时表示所有授权均已通过,跳转至首页。否则,将会一直停留在授权页。

//all authorize 
    let timer = setInterval(() => {
      this.authorizeInfo();
      if (this.data.userInfo && this.data.locationInfo){
        clearInterval(timer)                    
      }
    }, 100) 
  //authorizeInfo
  authorizeInfo: function(){
    if (this.data.userInfo && this.data.locationInfo) {
      this.setData({ authorizeInfo: true })
      //reLaunch
      wx.reLaunch({
        url: '/pages/index/index'
      })
 
    } else {
      this.setData({ authorizeInfo: false })
    }
  }

而重新授权这个操作需要调用wx.openSetting这个接口,通过返回值判断,用户再次调用授权操作后是否全部授权,是的话跳转至首页,否则停留在授权页。

//toAuthorize
  toAuthorize:function(){
    //重新调起授权
    wx.openSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
          this.setData({ authorizeInfo: true })
          //reLaunch
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }else{
          this.setData({ authorizeInfo: false })
        }
      },
      fail: (res) => {
        console.log("授权失败")
      }
    })

使用方法

  • 我的这个demo是个人信息加地理位置的双重授权
  • pages下的authorize文件夹是可以拿来直接用的 复制粘贴到你的pages下就可以了
  • 源码请移步GitHub >>>>>>> 戳我去看源码

相关文章

网友评论

      本文标题:微信小程序 如何在用户拒绝授权后重新授权

      本文链接:https://www.haomeiwen.com/subject/oykitftx.html