React-Native权限管理工具类
手下npm install react-native-permissions --save http://www.jianshu.com/p/e33fe3cb0e39
rnpm link 安装这个lib
详情https://github.com/yonahforst/react-native-permissions
但是使用其他还是比较麻烦,所以封装成工具类,最后可以这样使用
PermissionUtil.checkPermission(success,fail,["location"]);//成功调用 失败调用 权限
版本信息
代码如下:
/**
* Created by xq on 17/4/24.
*/
importReact, { Component }from'react';
import{
StyleSheet,
View,
StatusBar,
DeviceEventEmitter,
TouchableOpacity,
Text,
Alert,
Image
}from'react-native';
varPermissions= require('react-native-permissions');
classPermissionUtil{
checkPermission= (success,fail,permission = []) => {
letself=this;
letflag=true;
letper= [];
if(permission.length<=0){
return;
}
Permissions.checkMultiplePermissions(permission)
.then(status => {//直接修改设置 检测不到授权结果
Object.keys(status).map((k,v)=>{
if(status[k]=="authorized"){
}else{
per.push(k);
flag=false;
}
});
if(flag){
success();
}else{
if(per.length>0){
self.request(success,fail,per,0);
}
}
})
};
request= (success,fail,per,i)=>{
if(i
this.requestPermission(success,fail,per,i);
}else{
success();
}
};
requestPermission= (success,fail,per,i) => {
letself=this;
Permissions.requestPermission(per[i])
.then(res => {
if(res !='authorized') {
if(fail){
fail();
return;
}
switch(per[i]){
case"camera":
Alert.alert(
'无法使用!',
"请授予应用使用相机权限",
[
{text:'取消',style:'cancel'},
{text:'设置权限',onPress:Permissions.openSettings},
]
);
break;
case"photo":
Alert.alert(
'无法访问!',
"请授予应用访问存储sd卡权限",
[
{text:'取消',style:'cancel'},
{text:'设置权限',onPress:Permissions.openSettings},
]
);
break;
case"location":
Alert.alert(
'无法访问!',
"请授予应用访问位置信息权限",
[
{text:'取消',style:'cancel'},
{text:'设置权限',onPress:Permissions.openSettings},
]
);
break;
case"microphone":
Alert.alert(
'无法访问!',
"请授予应用录音权限",
[
{text:'取消',style:'cancel'},
{text:'设置权限',onPress:Permissions.openSettings},
]
);
break;
case"contacts":
Alert.alert(
'无法访问!',
"请授予应用获取联系人权限",
[
{text:'取消',style:'cancel'},
{text:'设置权限',onPress:Permissions.openSettings},
]
);
break;
default:
Alert.alert(
'无法访问!',
"请授予应用权限",
[
{text:'取消',style:'cancel'},
{text:'设置权限',onPress:Permissions.openSettings},
]
);
break;
}
}else{
self.request(success,fail,per,++i);
}
}).catch(e =>ConsoleLog.log(e))
};
}
export default newPermissionUtil();
以上是 React-Native权限管理工具类 的全部内容, 来源链接: utcz.com/z/384007.html