expo-duooomi-app/utils/permissions.ts

60 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Camera } from 'expo-camera'
import { Alert, Linking, Platform } from 'react-native'
/**
* 检查相机权限
* @returns Promise<boolean> 是否已授权
*/
export async function hasCameraPermission(): Promise<boolean> {
if (Platform.OS === 'web') return true
try {
const { status } = await Camera.getCameraPermissionsAsync()
return status === 'granted'
} catch (e) {
return false
}
}
/**
* 请求相机权限Promise风格
* @returns Promise<boolean> 是否已授权
*/
export async function requestCameraPermission(): Promise<boolean> {
if (Platform.OS === 'web') return true
try {
const { status } = await Camera.requestCameraPermissionsAsync()
return status === 'granted'
} catch (e) {
return false
}
}
/**
* 如果没有权限则弹窗提示并引导用户去设置
* @param message 提示内容
* @returns Promise<boolean> 是否已授权
*/
export async function ensureCameraPermission(message = '需要相机权限,请在设置中开启'): Promise<boolean> {
const granted = await hasCameraPermission()
if (granted) return true
const requested = await requestCameraPermission()
if (requested) return true
Alert.alert(
'权限提示',
message,
[
{ text: '取消', style: 'cancel' },
{
text: '去设置',
onPress: () => {
Linking.openSettings()
},
},
],
{ cancelable: true },
)
return false
}
// 可扩展:请求麦克风、相册等权限