const enumerateDevices = async () => { try { const devices = await navigator.mediaDevices.enumerateDevices(); return devices; } catch (errMsg) { return []; } }; const stopStreamTracks = (stream: MediaStream) => { if (!stream || !stream.getTracks) { return; } try { const tracks = stream.getTracks(); tracks.forEach(it => { try { it.stop(); } catch (errMsg) { } }); } catch (errMsg) { } }; const getCameraPermissionByAndroid = () => { const cameraPermission = "android.permission.CAMERA"; return new Promise((resolve) => { plus.android.requestPermissions( [cameraPermission], (e) => { const { granted } = e; const isGranted = granted.some((permission: string) => permission === cameraPermission); resolve(isGranted); }, (e) => { resolve(false); }, ); }); }; const getCameraPermissionByWeb = async () => { if (window.plus) { try { const isiOS = uni.getSystemInfoSync().platform === "ios"; const result = isiOS ? await getCameraPermissionByiOS() : await getCameraPermissionByAndroid(); if (!result) return false; } catch (err) { return false; } } const devices = await enumerateDevices(); if (devices.length === 0) return false; const constraints = devices.reduce( (info, device) => { if (!device) { return info; } if ('videoinput' === device.kind) { return { video: true, audio: info.audio }; } return info; }, { video: false, audio: false }, ); try { const stream = await navigator.mediaDevices.getUserMedia(constraints); stopStreamTracks(stream); } catch (errMsg) { if (errMsg && 'NotAllowedError' === errMsg.name) { return false; } } return true; }; const getCameraPermissionByiOS = () => { return new Promise((resolve) => { const avCaptureDevice = plus.ios.importClass("AVCaptureDevice"); const authStatus = avCaptureDevice.authorizationStatusForMediaType("vide"); plus.ios.deleteObject(avCaptureDevice); resolve(authStatus === 3); }); }; export const getCameraPermission = () => { // #ifdef WEB return getCameraPermissionByWeb(); // #endif // #ifdef APP const isiOS = uni.getSystemInfoSync().platform === "ios"; return isiOS ? getCameraPermissionByiOS() : getCameraPermissionByAndroid(); // #endif };