Published on

React Native 5단계: 디바이스 접근 (네이티브 기능 연동)

[5단계] 디바이스 접근 (네이티브 기능 연동)


1. Expo API로 디바이스 기능 사용하기

Expo는 많은 네이티브 기능을 간단하게 JS로 사용할 수 있게 포장해뒀다.

npx expo install expo-camera expo-location expo-media-library expo-notifications

2. 카메라 사용 (expo-camera)

import { Camera } from 'expo-camera';

const [permission, requestPermission] = Camera.useCameraPermissions();
const [ref, setRef] = useState(null);

<Camera style={{ flex: 1 }} ref={setRef} />
<Button title="촬영" onPress={async () => {
  const photo = await ref.takePictureAsync();
}} />
  • 첫 실행 시 권한 요청 필수
  • 촬영된 사진은 photo.uri로 접근 가능

3. 갤러리 접근 (expo-media-library)

import * as MediaLibrary from 'expo-media-library';

const [status, requestPermission] = MediaLibrary.usePermissions();

const savePhoto = async (photoUri) => {
  await MediaLibrary.saveToLibraryAsync(photoUri);
};
  • 촬영한 사진을 기기에 저장 가능

4. 위치 정보 얻기 (expo-location)

import * as Location from 'expo-location';

useEffect(() => {
  (async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') return;

    let location = await Location.getCurrentPositionAsync({});
    console.log(location.coords);
  })();
}, []);
  • GPS 정보, 위도/경도, 속도, 고도 등을 받아올 수 있음

5. 로컬 저장소 (AsyncStorage)

npx expo install @react-native-async-storage/async-storage
import AsyncStorage from '@react-native-async-storage/async-storage';

await AsyncStorage.setItem('user', JSON.stringify({ name: 'H.Y' }));
const data = await AsyncStorage.getItem('user');
  • 로그인 정보, 간단한 캐시 등 로컬 저장용

6. 푸시 알림 (expo-notifications)

npx expo install expo-notifications
import * as Notifications from 'expo-notifications';

Notifications.scheduleNotificationAsync({
  content: { title: "Hello", body: "푸시 알림 왔어요" },
  trigger: { seconds: 5 },
});
  • Expo 서버 기반 푸시 시스템 제공
  • 앱 푸시를 사용하려면 토큰 발급 → 서버에서 전송 구조 필요

요약

  • Expo만으로도 카메라, 위치, 저장소, 알림 등의 기본 네이티브 기능을 쉽게 제어할 수 있음
  • 항상 권한 요청 먼저 처리하고, 결과값은 비동기로 받아야 함
  • 실사용 기능이므로 에러 처리, 사용자 피드백 필수

심화학습

Q1. Expo를 쓰다가 네이티브 기능이 제한될 때는 어떻게 해야 하나요?
A1. expo eject 명령으로 프로젝트를 React Native CLI로 전환하면 직접 네이티브 모듈을 연결할 수 있다. 다만 Xcode/Android Studio가 필요하고 빌드 환경이 복잡해진다.


Q2. AsyncStorage는 어떤 데이터 저장용으로 적절한가요?
A2. 간단한 문자열, JSON 객체, 사용자 설정 등을 저장하기 좋다. 민감하거나 대용량 데이터에는 적합하지 않으며, DB 수준의 처리가 필요하면 SQLite를 고려해야 한다.


Q3. 위치 정보나 카메라 접근 시 사용자 경험을 좋게 하려면 어떻게 해야 하나요?
A3. 앱 처음 실행 시 미리 권한 요청하고, 거부되었을 경우에는 설정 페이지로 유도하거나 대체 화면을 제공하는 게 좋다. 또한 로딩 중에는 Spinner나 Skeleton UI로 사용자에게 명확한 상태를 알려줘야 한다.