Day 4 of 5

Native Device Features

Expo gives you access to the camera, location, notifications, and more through a set of managed APIs. Today you will request permissions, access the camera roll, and read the device location.

bash
npx expo install expo-camera expo-location expo-image-picker
jsx
// CameraExample.js
import { useState } from 'react';
import { Button, Image, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function CameraExample() {
  const [image, setImage] = useState(null);

  async function pickImage() {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') return alert('Permission denied');

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 0.7,
    });

    if (!result.canceled) setImage(result.assets[0].uri);
  }

  return (
    <View style={{ flex:1, alignItems:'center', padding:20 }}>
      <Button title="Pick an image" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width:300, height:225, marginTop:16 }} />}
    </View>
  );
}
jsx
// LocationExample.js
import { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import * as Location from 'expo-location';

export default function LocationExample() {
  const [loc, setLoc] = useState(null);

  useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') return;
      const pos = await Location.getCurrentPositionAsync({});
      setLoc(pos.coords);
    })();
  }, []);

  return (
    <View style={{ padding:20 }}>
      {loc ? <Text>{loc.latitude.toFixed(4)}, {loc.longitude.toFixed(4)}</Text>
           : <Text>Getting location...</Text>}
    </View>
  );
}

Exercise: Build a Location Tagger

  1. Request location permission on app start
  2. Get current lat/lng and reverse-geocode to city
  3. Let user take a photo with the camera
  4. Overlay the city name on the photo preview
  5. Save the tagged photo to the camera roll

Day 4 Summary

Finished this lesson?