안녕하세요. 모리스입니다.😀
이번 포스트는 재미난 라이브러리 하나를 소개해 보려합니다.!
React Native에서 휴대폰 디바이스의 내장 센서를 사용할 수 있도록 해주는 react-native-sensors라는 라이브러리 입니다.
자, 그럼 시작해 볼게요!
🔎 react-native-sensors란?
react-native-sensors 라이브러리는 React Native 앱에서 휴대폰 디바이스의 내장 센서를 사용할 수 있도록 도와줍니다.
이 라이브러리를 통해 다음과 같은 센서 정보를 다룰 수 있어요:
- 가속도계 (Accelerometer)
- 자이로스코프 (Gyroscope)
- 지자기계 (Magnetometer)
- 기압계 / 바로미터 (Barometer)
🛠 설치 방법
- 라이브러리 설치 (iOS는 pod install도 함께)
npm install --save react-native-sensors
- Native 모듈 연동이 필요하다면:
react-native link react-native-sensors
- 권한 설정
- Android: AndroidManifest.xml에 아래 권한 추가
<uses-permission android:name="android.permission.BODY_SENSORS" />
- iOS: Info.plist에 권한 문구 추가
<key>NSMotionUsageDescription</key>
<string>센서를 사용하는 이유를 여기에 작성</string>
📦 사용 예시
센서 데이터는 보통 컴포넌트가 mount될 때 구독을 시작하고, unmount 시점에 구독을 해제하는 방식으로 사용합니다.
아래는 Hook을 사용한 가속도계 구독 예시입니다:
import { accelerometer } from 'react-native-sensors';
import { useEffect } from 'react';
useEffect(() => {
const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) => {
console.log('x, y, z, timestamp:', x, y, z, timestamp);
});
return () => subscription.unsubscribe();
}, []);
위 코드는 디바이스가 움직일 때마다 가속도 데이터를 실시간으로 출력합니다.
⏱ 업데이트 주기 설정
센서 데이터는 기본적으로 100ms 주기로 업데이트되며, 필요에 따라 주기를 변경할 수 있습니다.
다만 Android에서는 0ms 이하의 업데이트는 지원되지 않으니 주의하세요!
import { setUpdateIntervalForType, SensorTypes, accelerometer } from 'react-native-sensors';
import { useEffect } from 'react';
useEffect(() => {
// 가속도계 데이터 업데이트를 1초에 한 번으로 설정
setUpdateIntervalForType(SensorTypes.accelerometer, 1000);
const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) => {
console.log('x, y, z, timestamp:', x, y, z, timestamp);
});
return () => subscription.unsubscribe();
}, []);
이제 가속도 센서는 1초마다 데이터를 업데이트합니다.
기본값은 100ms이니 상황에 따라 조절하세요.
📚 공식 문서
React Native Sensors · Get your Accelerometer, Gyroscope, Magnetometer, and Barometer data the easy and reactive way
Get your Accelerometer, Gyroscope, Magnetometer, and Barometer data the easy and reactive way
react-native-sensors.github.io
'React Native' 카테고리의 다른 글
[React Native] aspectRatio (2) | 2025.04.12 |
---|---|
[React Native] Kakao Login (0) | 2025.04.12 |
[React Native] react-native-masked-text 사용법 (0) | 2025.04.08 |
[React Native] React Native Tools (0) | 2025.04.07 |
[React Native] NotoSans 사용 시 예상치 못한 패딩 문제 해결하기 (feat. Android) (0) | 2025.04.07 |