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