ryuyoonju 2024-08-01
240801 류윤주
@7d5aa6b19b73682fd4fd974e65b101b804288aa9
src/screen/CameraScreen.js
--- src/screen/CameraScreen.js
+++ src/screen/CameraScreen.js
@@ -1,125 +1,87 @@
-import React, { useEffect, useState, useRef } from 'react';
-import { View, Button, StyleSheet, Alert, Text, Linking } from 'react-native';
-import { Camera, useCameraDevices } from 'react-native-vision-camera';
-import { useNavigation } from '@react-navigation/native';
+import React, { useEffect, useState } from 'react';
+import { View, Text, StyleSheet, Alert } from 'react-native';
+import { Camera, useCameraDevice, useCameraPermission } from 'react-native-vision-camera';
 
 const CameraScreen = () => {
-    const [hasPermission, setHasPermission] = useState(false);
-    const [isDeviceReady, setIsDeviceReady] = useState(false);
-    const devices = useCameraDevices();
-    const device = devices.front;
-    const camera = useRef(null);
-    const navigation = useNavigation();
+  const [loading, setLoading] = useState(true);
+  const { status: permissionStatus, requestPermission } = useCameraPermission();
+  const device = useCameraDevice('back'); // 'front' 또는 'back'
 
-    // Function to check and request camera permission
-    const checkPermission = async () => {
-        const cameraPermission = await Camera.getCameraPermissionStatus();
-        console.log(cameraPermission)
-        if (cameraPermission === 'granted') {
-            setHasPermission(true);
-            setIsDeviceReady(true);
-        } else if (cameraPermission === 'not-determined') {
-            const newCameraPermission = await Camera.requestCameraPermission();
-            if (newCameraPermission === 'granted') {
-                setHasPermission(true);
-                setIsDeviceReady(true);
-            } else {
-                setHasPermission(false);
-                Alert.alert('카메라 권한 필요', '카메라 권한이 필요합니다.', [
-                    { text: '설정으로 이동', onPress: () => Linking.openSettings() },
-                    { text: '취소', style: 'cancel' },
-                ]);
-            }
+  useEffect(() => {
+    const checkPermissions = async () => {
+      try {
+        console.log('Checking camera permission status...');
+        if (permissionStatus === 'not-determined') {
+          console.log('Requesting camera permission...');
+          const newStatus = await requestPermission();
+          console.log('New camera permission status:', newStatus);
         } else {
-            setHasPermission(false);
-            Alert.alert('카메라 권한 필요', '카메라 권한이 필요합니다.', [
-                { text: '설정으로 이동', onPress: () => Linking.openSettings() },
-                { text: '취소', style: 'cancel' },
-            ]); 
+          console.log('Current permission status:', permissionStatus);
         }
+      } catch (error) {
+        console.error('Error checking permissions:', error);
+        Alert.alert('Error', 'An error occurred while checking permissions.');
+      }
     };
 
-    useEffect(() => {
-        // Check permission once on component mount
-        checkPermission();
-    }, []);
+    checkPermissions();
+  }, [permissionStatus, requestPermission]);
 
-    useEffect(() => {
-        // Update the device readiness when the camera device changes
-        if (device) {
-            setIsDeviceReady(true);
-        } else {
-            setIsDeviceReady(false);
-        }
-    }, [device]);
+  useEffect(() => {
+    console.log('Device:', device); // 디바이스 정보 로그 추가
 
-    const handleCapture = async () => {
-        if (camera.current) {
-            try {
-                const photo = await camera.current.takePhoto({
-                    flash: 'off',
-                    qualityPrioritization: 'speed',
-                });
-                console.log('Photo taken:', photo);
-                navigation.navigate('Gps'); // Move to the next screen after capturing photo
-            } catch (error) {
-                console.error('Photo capture error:', error.message);
-                Alert.alert('오류', '사진 캡처 중 오류가 발생했습니다.');
-            }
-        }
-    };
+    if (device) {
+      console.log('Camera device loaded:', device);
+      setLoading(false);
+    } else {
+      console.log('No camera device found');
+      setLoading(false); // No device found 시에도 로딩 상태를 false로 설정
+    }
+  }, [device]);
 
-    if (!hasPermission) {
-        return (
-            <View style={styles.permissionContainer}>
-                <Text>카메라 권한을 요청 중입니다...</Text>
-            </View>
-        );
+  const renderCamera = () => {
+    if (loading) {
+      return <Text>Loading camera...</Text>;
     }
 
-    return (
-        <View style={styles.container}>
-            {isDeviceReady && device ? (
-                <Camera
-                    ref={camera}
-                    style={StyleSheet.absoluteFill}
-                    device={device}
-                    photo={true}
-                    video={false}
-                    isActive={true}
-                />
-            ) : (
-                <View style={styles.buttonContainer}>
-                    <Text>카메라 장치 준비 중...</Text>
-                    <Button title="다음 페이지로 이동" onPress={() => navigation.navigate('Gps')} />
-                </View>
-            )}
-            <Button title="Capture" onPress={handleCapture} style={styles.captureButton} />
+    if (!device) {
+      return <Text>No camera device found</Text>;
+    }
+
+    if (permissionStatus === 'granted') {
+      return <Camera style={styles.camera} device={device} isActive={true} photo={true}/>;
+    } else {
+      return (
+        <View style={styles.noPermission}>
+          <Text>Camera access is not granted. Please enable camera permissions in settings.</Text>
         </View>
-    );
+      );
+    }
+  };
+
+  return (
+    <View style={styles.container}>
+      {renderCamera()}
+    </View>
+  );
 };
 
 const styles = StyleSheet.create({
-    container: {
-        flex: 1,
-        justifyContent: 'center',
-        alignItems: 'center',
-    },
-    buttonContainer: {
-        justifyContent: 'center',
-        alignItems: 'center',
-        flex: 1,
-    },
-    captureButton: {
-        position: 'absolute',
-        bottom: 20,
-        alignSelf: 'center',
-    },
-    permissionContainer: {
-        flex: 1,
-        justifyContent: 'center',
-        alignItems: 'center',
-    },
+  container: {
+    flex: 1,
+    justifyContent: 'center',
+    alignItems: 'center',
+  },
+  camera: {
+    width: '100%',
+    height: '100%',
+  },
+  noPermission: {
+    flex: 1,
+    justifyContent: 'center',
+    alignItems: 'center',
+    padding: 20,
+  },
 });
 
 export default CameraScreen;
Add a comment
List