Device APIへのアクセス:Camera、Location、Push Notifications
Expo SDK modulesを使って権限をリクエストし、ネイティブデバイスの機能にアクセスします。
「Device APIへのアクセス:Camera、Location、Push Notifications」はCoddyKit上の無料React Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはReact Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 React Academyコースには全4レッスンが含まれています。
Expo SDKモジュール
Expo SDKは、ネイティブデバイスの機能を利用するためのJavaScript APIを提供します。パッケージを個別にインストールし、ハードウェアにアクセスする前に権限をリクエストします。
# Install what you need:
npx expo install expo-camera expo-location expo-notifications権限のリクエスト
デバイスの機密性の高い機能にアクセスする前に、必ず権限をリクエストします。処理を続行する前に、結果を確認します。
import * as Location from 'expo-location';
async function getLocation() {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
Alert.alert('Permission denied');
return;
}
const location = await Location.getCurrentPositionAsync({});
console.log(location.coords);
}カメラへのアクセス
expo-cameraを使うと、カメラのプレビューを表示して写真を撮影できます。
import { CameraView, useCameraPermissions } from 'expo-camera';
import { useRef } from 'react';
export function CameraScreen() {
const [permission, requestPermission] = useCameraPermissions();
const cameraRef = useRef(null);
if (!permission?.granted) {
return <Button onPress={requestPermission} title="Grant camera" />;
}
const takePicture = async () => {
const photo = await cameraRef.current?.takePictureAsync();
console.log(photo?.uri);
};
return <CameraView ref={cameraRef} facing="back" />;
}画像選択
expo-image-pickerを使うと、カメラのUIを表示せずに、ユーザーがカメラロールから画像を選択できます。
import * as ImagePicker from 'expo-image-picker';
async function pickImage() {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
quality: 0.8,
allowsEditing: true,
aspect: [4, 3],
});
if (!result.canceled) {
console.log(result.assets[0].uri);
}
}位置情報の追跡
リアルタイムで追跡するには、watchPositionAsync()を使って位置情報の更新を購読します。アンマウント時に購読を解除します。
useEffect(() => {
let subscription;
(async () => {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') return;
subscription = await Location.watchPositionAsync(
{ accuracy: Location.Accuracy.High, distanceInterval: 10 },
location => setCoords(location.coords)
);
})();
return () => subscription?.remove();
}, []);ジオコーディングと逆ジオコーディング
expo-locationを使うと、座標を住所に変換する逆ジオコーディングや、住所を座標に変換するジオコーディングを実行できます。
const [address] = await Location.reverseGeocodeAsync({ latitude: 37.78, longitude: -122.43 });
console.log(`${address.street}, ${address.city}, ${address.country}`);プッシュ通知の設定
expo-notificationsを使ってプッシュ通知に登録し、Expoプッシュトークンを取得します。
import * as Notifications from 'expo-notifications';
async function registerForPushNotifications() {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') return null;
const token = (await Notifications.getExpoPushTokenAsync()).data;
return token; // send this to your server
}受信した通知の処理
アプリがフォアグラウンドにあるときの通知や、通知をタップしたときのイベントを監視します。
useEffect(() => {
const receivedSub = Notifications.addNotificationReceivedListener(notification => {
console.log('Received:', notification);
});
const responseSub = Notifications.addNotificationResponseReceivedListener(response => {
const data = response.notification.request.content.data;
router.push(`/post/${data.postId}`);
});
return () => { receivedSub.remove(); responseSub.remove(); };
}, []);ローカル通知
サーバーを必要としないローカル通知を、scheduleNotificationAsyncでスケジュールします。
await Notifications.scheduleNotificationAsync({
content: { title: 'Reminder', body: 'Check your app!', data: {} },
trigger: { seconds: 60 }, // fires after 60 seconds
});バックグラウンドでの位置情報
バックグラウンドで位置情報を取得するには、expo-task-managerとLocation.startLocationUpdatesAsyncを使います。app.jsonに追加の権限設定が必要です。
理解度チェック
Expoでデバイスのカメラや位置情報にアクセスする前に、必ず何をする必要がありますか。
まとめ
デバイスにアクセスするには、Expo SDKモジュール(expo-camera、expo-location、expo-notifications)を使います。まず必ず権限をリクエストして結果を確認し、useEffect内で購読を解除します。プッシュ通知に登録し、Expoプッシュトークンをバックエンドに送信します。
AI チューターと学ぶ React — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 88
- レッスン
- 324
よくある質問
「Device APIへのアクセス:Camera、Location、Push Notifications」レッスンは無料ですか?
はい。「Device APIへのアクセス:Camera、Location、Push Notifications」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、React Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 React Academyコースには全4レッスンが含まれています。
「Device APIへのアクセス:Camera、Location、Push Notifications」で何を学びますか?
Expo SDK modulesを使って権限をリクエストし、ネイティブデバイスの機能にアクセスします。 ブラウザで直接実行するハンズオンコードでReact Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
React Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのReact Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「Device APIへのアクセス:Camera、Location、Push Notifications」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このReact Academyレッスンでコードを書いて実行できますか?
はい。すべてのReact Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- React Native Core ComponentsとWeb DOMの比較
- StyleSheet APIとFlexboxによるスタイリング
- Expo Routerによるナビゲーション
- Device APIへのアクセス:Camera、Location、Push Notifications