参考 黑马 的教学视频
一、获取权限
获取权限,有三种情况
1、用户从来没有获取过,所以这个的权限 scope = undefined
2、用户获取过,同意了,权限 scope = true
3、用户拒绝了,scope = false
4、当用户拒绝了,便无法再为这个权限使用
解决方法:
1、诱导用户 自己 打开 授权设置页面(wx.openSetting)
以下以获取用户地址为例
原生版本
获取 用户 对小程序 所授予 获取地址的 权限 状态 scope
-
假设 用户 点击获取收货地址的提示框 确定 authSetting scope.address scope 值 true 直接调用 获取收货地址
-
假设 用户 从来没有调用过 收货地址的api
scope undefined 直接调用 获取收货地址
-
假设 用户 点击获取收货地址的提示框 取消
scope 值 false
3-1 诱导用户 自己 打开 授权设置页面(wx.openSetting) 当用户重新给与 获取地址权限的时候
3-2 获取收货地址
3-3 把获取到的收货地址 存入到 本地存储中
// 2 获取 用户 对小程序 所授予 获取地址的
wx.getSetting({
success: (result)=>{
// 权限 状态 scope
const scopeAddress = result.authSetting["scope.address
// 1 假设 用户 点击获取收货地址的提示框 确定 authSetting scope.address
// scope 值 true 直接调用 获取收货地址
// 2 假设 用户 从来没有调用过 收货地址的api
// scope undefined 直接调用 获取收货地址
if(scopeAddress === true || scopeAddress === undefined) {
wx.chooseAddress({
success: (result1)=>{
console.log(result1)
}
});
}else {
// 3 假设 用户 点击获取收货地址的提示框 取消
// scope 值 false
// 1 诱导用户 自己 打开 授权设置页面(wx.openSetting) 当用户重新给与 获取地址权限的时候
// 2 获取收货地址
wx.openSetting({
success: (result2)=>{
// 4 把获取到的收货地址 存入到 本地存储中
wx.chooseAddress({
success: (result3)=>{
console.log(result3)
}
});
}
});
}
}
});
优化版本
新添加一个js文件,使用async,await 优化回调地狱
/**
* primise 形式 getSetting
*/
export const getSetting = () => {
return new Promise((resolve, reject) => {
wx.getSetting({
success: (result)=>{
resolve(result);
},
fail: (err)=>{
reject(err);
},
complete: ()=>{}
});
})
}
/**
* primise 形式 chooseAddress
*/
export const chooseAddress = () => {
return new Promise((resolve, reject) => {
wx.chooseAddress({
success: (result)=>{
resolve(result);
},
fail: (err)=>{
reject(err);
},
complete: ()=>{}
});
})
}
/**
* primise 形式 openSetting
*/
export const openSetting = () => {
return new Promise((resolve, reject) => {
wx.openSetting({
success: (result)=>{
resolve(result);
},
fail: (err)=>{
reject(err);
},
complete: ()=>{}
});
})
}
// 引入简化的 promise
import { getSetting, chooseAddress, openSetting } from "../../utils/asyncWx.js";
// 引入es7语法解析
import regeneratorRuntime from "../../lib/runtime/runtime";
// 简化的操作
try {
// 1 获取 权限状态
const res1 = await getSetting()
const scopeAddress = res1.authSetting["scope.address"];
// 2 判断 权限状态
if (scopeAddress === false)
// 3 打开授权设置页面
await openSetting
// 4 调用获取收货地址的 api
const res2 = await chooseAddress();
console.log(re
// 5 把获取到的收货地址 存入到 本地存储中
wx.setStorageSync("address", res
} catch (err) {
console.log(err)
}