In this lesson Mrs. Rini's Laundry app gets two new buttons: "Scan receipt", which reads the QR on the paper receipt with the camera, and "Use my current location", which fills in the pickup address from GPS. The camera, GPS and sensors are phone hardware an app may use, as long as the owner allows it. The rules are like those for Mrs. Rini's courier coming to collect the laundry: he can't walk into the house without permission, he has to say what for ("I'm here for the laundry"), and Wulan may give him the exact address or just "near the mosque". An app works the same way: ask for permission, write down the reason, and accept it when the user only shares an approximate location.
Permission first, with a clear reason
npx expo install expo-camera expo-location # SDK 57: 57.0.6 and 57.0.20
{
"expo": {
"plugins": [
["expo-camera", { "cameraPermission": "Allow Mrs. Rini's Laundry to photograph your laundry receipts.", "microphonePermission": false, "recordAudioAndroid": false }],
["expo-location", { "locationWhenInUsePermission": "Allow Mrs. Rini's Laundry to use your location for the pickup address." }]
]
}
}
After npx expo prebuild, Info.plist holds NSCameraUsageDescription and NSLocationWhenInUseUsageDescription with those two sentences, and AndroidManifest.xml holds CAMERA, ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION. That reason sentence is what the iOS dialog shows. Without the option, the plugin writes a default English text, for example Allow $(PRODUCT_NAME) to access your camera.
- The dialog rules are the same as in the platform lesson: iOS asks once, Android twice (since Android 11). After that
canAskAgainisfalse, and the only way left isLinking.openSettings(). - Ask when the button is tapped, not when the app opens.
- Prebuild also writes two "Always" location keys with the default English text. They only show if the app asks for background location, and this app doesn't.
Scanning the receipt QR with expo-camera
Every receipt has a QR holding the order code, for example RL-13.
// src/components/ScanReceipt.tsx
import { CameraView, useCameraPermissions, type BarcodeScanningResult } from 'expo-camera';
import { router } from 'expo-router';
import { useRef } from 'react';
import { Button, Linking } from 'react-native';
const RECEIPT_PATTERN = /^RL-(\d{1,6})$/; // the receipt QR holds: RL-13
export default function ScanReceipt() {
const [permission, requestPermission] = useCameraPermissions();
const scanned = useRef(false);
if (!permission) return null; // permission status not read yet
if (!permission.granted) {
return permission.canAskAgain
? <Button title="Allow the camera to scan receipts" onPress={requestPermission} />
: <Button title="Open Settings" onPress={() => Linking.openSettings()} />;
}
function onScan({ data }: BarcodeScanningResult) {
if (scanned.current) return; // fires again and again while the QR is in view
const match = RECEIPT_PATTERN.exec(data);
if (!match) return; // some other QR (a promo, a strange link): ignore it
scanned.current = true;
router.push(`/order/${match[1]}`); // the server still checks: someone else's order = 404
}
return <CameraView style={{ flex: 1 }} facing="back" barcodeScannerSettings={{ barcodeTypes: ['qr'] }} onBarcodeScanned={onScan} />;
}
CameraViewshows the camera.barcodeScannerSettingslimits it to QR codes, andonBarcodeScannedreceives{ type: 'qr', data: 'RL-13', ... }.- The callback fires many times while the QR is in front of the camera. Without
scanned, the Order #13 screen could open several times. - The QR's content comes from paper, so check its shape.
RL-12passes the pattern, but it's Mr. Darto's order:GET /api/orders/12answers404, and the screen shows "Order not found". - Only one camera preview may be active. Unmount
CameraViewwhen its screen is left. - Other libraries:
react-native-vision-camera(5.2.3 on npm) for heavy needs like processing every frame; it needs a development build. To just take or pick a photo,expo-image-pickeropens the system camera or gallery.
Location for the pickup address
// src/lib/location.ts
import * as Location from 'expo-location';
export async function pickupLocation() {
const permission = await Location.requestForegroundPermissionsAsync();
if (!permission.granted) return null; // the address can still be typed by hand
const position = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High }); // about 10 m
const { latitude, longitude, accuracy } = position.coords; // accuracy: the uncertainty radius, in metres
const [address] = await Location.reverseGeocodeAsync({ latitude, longitude });
return { latitude, longitude, accuracyMeters: accuracy, address };
}
The code above sets accuracy on purpose. Guess first: if the "Use my current location" button calls getCurrentPositionAsync() with no options, how many metres is the courier's point accurate to?
Location.Accuracy |
Value | Accurate to |
|---|---|---|
Lowest |
1 | 3 km |
Low |
2 | 1 km |
Balanced |
3 | 100 m (default) |
High |
4 | 10 m |
Highest |
5 | the best available |
BestForNavigation |
6 | the highest, plus sensor data, for navigation |
With no options, getCurrentPositionAsync() uses Balanced: accurate to about 100 metres, enough for "which neighbourhood", too rough for Wulan's gate. For the pickup address, ask for High once.
- Battery: low accuracies can avoid GPS, the hungriest provider. Take the position once with
getCurrentPositionAsync, notwatchPositionAsyncrunning nonstop. Getting a fix can take several seconds;getLastKnownPositionAsync({ maxAge: 60000 })is faster when a position from a minute ago is good enough. - Approximate location: since Android 12 and iOS 14, users can choose "approximate". You get
permission.android?.accuracy === 'coarse'orpermission.ios?.accuracy === 'reduced', and asking forHighdoesn't change that. Show a manual address field. reverseGeocodeAsyncturns coordinates into an address. Call it once per tap, not in a loop.
Sensors: use them only when needed
expo-sensors (57.0.3) gives you Accelerometer, Barometer, DeviceMotion, Gyroscope, LightSensor, Magnetometer and Pedometer. This laundry app needs none of them, so it doesn't install it. If a feature needs one (shake the phone to report a problem, say), remove the listener with sub.remove() when its screen is left, set motionPermission for iOS, and remember Android 12 and up caps readings at 200 Hz.
Simulators and emulators
| iOS Simulator | Android emulator | Real phone | |
|---|---|---|---|
| Camera and QR scanning | no camera | the expo-camera docs mark it "device only" | yes |
| Location | pick one from the Device > Location menu | turn Location on in the emulator's settings, set the point from the emulator | yes, including the "approximate" choice |
So scan the receipt on a real phone. Location can be tested in a simulator, with a made-up point.
⚠️ Double scans, rough locations and a drained battery
- Opening the order screen on every
onBarcodeScannedcall. Lock it withuseRefafter the first matching scan. - Trusting the QR's content. Check its shape, and let the server decide whose order it is.
getCurrentPositionAsync()withoutaccuracy. The default isBalanced, about 100 m.- Forgetting the permission reason. Without
cameraPermissionandlocationWhenInUsePermission, iOS shows the default English text. - Leaving
watchPositionAsyncrunning. The GPS stays on and the battery drains fast. Take one reading, orremove()the subscription.
TL;DR: The camera and location need permission plus a reason sentence from the config plugin (cameraPermission, locationWhenInUsePermission), written into Info.plist and AndroidManifest.xml at prebuild. iOS asks once, Android twice, then Linking.openSettings(). The usual camera libraries: expo-camera or react-native-vision-camera. CameraView with barcodeTypes: ['qr'] reads RL-13 from the receipt; lock after the first scan, check the pattern, and let the server answer 404 for someone else's order. getCurrentPositionAsync() defaults to Balanced (about 100 m); for the pickup address ask for Accuracy.High (about 10 m) once, and keep a manual address for approximate location. Install sensors only when a feature needs them. Scanning is tested on a real phone; location can be tested in a simulator.
⚡ Permission with a reason
Write:
["expo-location", { "locationWhenInUsePermission": "Allow Mrs. Rini's Laundry to use your location for the pickup address." }]
Meaning: This reason sentence is what the iOS permission dialog shows. Without that option, the plugin writes a default English text. Ask for the permission when the button is tapped, not when the app opens.
⚡ Scan only once
Write:
if (scanned.current) return; // fires again and again while the QR is in view
const match = RECEIPT_PATTERN.exec(data);
if (!match) return; // some other QR (a promo, a strange link): ignore it
scanned.current = true;
router.push(`/order/${match[1]}`);
Meaning: onBarcodeScanned fires many times while the QR is in front of the camera. Lock it with useRef after the first scan that matches the pattern. The QR's content comes from paper, so the server still decides whose order it is.
⚡ How accurate is the location
Guess first: the "Use my current location" button calls getCurrentPositionAsync() with no options. How many metres is the courier's point accurate to?
About 100 metres. With no options the accuracy is Balanced: enough for "which neighbourhood", too rough for Wulan's gate.
Meaning: For the pickup address, ask for Accuracy.High (about 10 m) once, not watchPositionAsync running nonstop and draining the battery.