Tapping into Native Device Features

11 min read

Tapping into Native Device Features 📱

Welcome, intrepid coder! So, you've been building beautiful user interfaces with React Native, making buttons that sing and lists that scroll for days. But let's be honest, an app that only talks to itself is like a superhero who never leaves their secret lair. It's time to unleash the full potential of your creations by letting them interact with the world around them – through the device's own hardware!

This guide is your key to unlocking the treasure chest of native device features. We'll be the calm, cool, and collected guides on your journey from a sandboxed app to one that can see, feel, and know its place in the world (literally!).


1. Requesting & Handling Device Permissions 🙏

The Problem: Imagine you're building a delivery app. To show the user their location on a map, you need access to their GPS. But you can't just barge in and take that information! Operating systems like iOS and Android are very protective of user privacy. They act like a strict bouncer at a club, and you need to be on the guest list to get in. If you try to access sensitive information without permission, your app will be unceremoniously shown the door (i.e., it will crash or simply not work).

The Solution: You need to politely ask the user for permission. This is where the concept of device permissions comes in. You present a request to the user, explaining why you need access, and they have the final say.

In the world of React Native, we often rely on third-party libraries to handle the nitty-gritty details of platform-specific permission systems. One of the most popular and battle-tested libraries for this is react-native-permissions.

Getting Started with react-native-permissions

First things first, let's get this powerhouse of a library into our project.

Installation:

Open your terminal, navigate to your React Native project directory, and run:

bash
# For npm users
npm install react-native-permissions

# For yarn users
yarn add react-native-permissions

Next, you'll need to install the pods for iOS:

bash
cd ios && pod install && cd ..

Configuration:

This is where you tell the operating systems what permissions your app might ask for.

iOS (ios/YourProjectName/Info.plist):

You need to add keys to your Info.plist file that describe why you're asking for a particular permission. This message will be shown to the user in the permission dialog. Be clear and concise!

For example, to request photo library access, you would add:

xml
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to let you pick a profile picture.</string>

Android (android/app/src/main/AndroidManifest.xml):

For Android, you declare the permissions you'll be using in the AndroidManifest.xml file.

xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Checking and Requesting Permissions

Now for the fun part! Let's see how to actually ask for permission in your code. The flow is usually:

  1. Check if you already have the permission.
  2. If not, request it.
  3. Handle the user's response.

Here's a simple example of how to request camera permission:

javascript
import React, {useEffect} from 'react';
import {View, Button, Alert, Platform} from 'react-native';
import {PERMISSIONS, request, check, RESULTS} from 'react-native-permissions';

const App = () => {
  const requestCameraPermission = async () => {
    try {
      const platformPermission = Platform.OS === 'ios'
        ? PERMISSIONS.IOS.CAMERA
        : PERMISSIONS.ANDROID.CAMERA;

      const result = await check(platformPermission);

      switch (result) {
        case RESULTS.UNAVAILABLE:
          Alert.alert('Error', 'This feature is not available on this device');
          break;
        case RESULTS.DENIED:
          const requestResult = await request(platformPermission);
          if (requestResult === RESULTS.GRANTED) {
            Alert.alert('Success', 'Camera permission granted');
          } else {
            Alert.alert('Error', 'Camera permission denied');
          }
          break;
        case RESULTS.LIMITED:
          Alert.alert('Info', 'Camera permission is limited');
          break;
        case RESULTS.GRANTED:
          Alert.alert('Info', 'Camera permission is already granted');
          break;
        case RESULTS.BLOCKED:
          Alert.alert(
            'Error',
            'Camera permission is blocked. Please enable it in the settings.',
          );
          break;
      }
    } catch (err) {
      console.warn(err);
    }
  };

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Button title="Request Camera Permission" onPress={requestCameraPermission} />
    </View>
  );
};

export default App;

What's happening here?

  • We use check to see the current status of the permission.
  • The RESULTS object gives us different states like GRANTED, DENIED, BLOCKED (the user denied and said "don't ask again"), etc.
  • If the permission is DENIED, it means we can still ask. So, we call request.
  • We then handle the outcome of the request.

Industry Practice: Always provide a clear explanation to the user before the permission dialog pops up. This increases the chances of them granting it. A simple modal explaining "We need camera access to let you scan QR codes" goes a long way!


2. Accessing the Device Camera & Photo Library 📸

The Problem: Your amazing new social media app needs a way for users to set a profile picture. Or maybe you're building a document scanner. In either case, you need to access the device's camera or its photo library. How do you bridge the gap between your React Native code and the device's hardware?

The Solution: We'll use another fantastic library, react-native-image-picker, to handle this for us. It provides a simple way to launch the camera or the image library and get the selected image back into our app.

Getting Started with react-native-image-picker

Installation:

bash
# For npm users
npm install react-native-image-picker

# For yarn users
yarn add react-native-image-picker

And for iOS, install the pods:

bash
cd ios && pod install && cd ..

Configuration:

Just like with permissions, you need to tell the OS why you need access.

iOS (ios/YourProjectName/Info.plist):

xml
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select a photo.</string>
<key>NSCameraUsageDescription</key>
<string>We need access to your camera to take a photo.</string>

Android (android/app/src/main/AndroidManifest.xml):

You'll need to add permissions here if they aren't already present from the previous step. The library will often need storage permissions as well.

xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Launching the Camera and Image Library

Let's see this in action. We'll create a simple component with two buttons: one to launch the camera and another to open the image library.

javascript
import React, {useState} from 'react';
import {View, Button, Image, Alert} from 'react-native';
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';

const App = () => {
  const [imageUri, setImageUri] = useState(null);

  const openCamera = async () => {
    const options = {
      mediaType: 'photo',
      quality: 1,
    };

    await launchCamera(options, response => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.errorCode) {
        console.log('ImagePicker Error: ', response.errorMessage);
        Alert.alert('Error', 'An error occurred');
      } else {
        const source = {uri: response.assets[0].uri};
        setImageUri(source);
      }
    });
  };

  const openImageLibrary = async () => {
    const options = {
      mediaType: 'photo',
      quality: 1,
    };

    await launchImageLibrary(options, response => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.errorCode) {
        console.log('ImagePicker Error: ', response.errorMessage);
        Alert.alert('Error', 'An error occurred');
      } else {
        const source = {uri: response.assets[0].uri};
        setImageUri(source);
      }
    });
  };


  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      {imageUri && (
        <Image source={imageUri} style={{width: 200, height: 200, marginBottom: 20}} />
      )}
      <Button title="Open Camera" onPress={openCamera} />
      <Button title="Open Image Library" onPress={openImageLibrary} />
    </View>
  );
};

export default App;

What's going on?

  • We import launchCamera and launchImageLibrary from the library.
  • We define some options. react-native-image-picker is highly customizable! You can specify if you want a photo or video, the quality, and more.
  • The callback gives us a response object. We check if the user canceled or if there was an error.
  • If everything is successful, we get an array of assets. We take the uri of the first asset and use it to display the image.

Fun Fact: Under the hood, these libraries are calling native Objective-C/Swift (for iOS) and Java/Kotlin (for Android) code. React Native's "bridge" allows your JavaScript code to communicate with these native modules. It's like having a very efficient translator for two different languages!


3. Getting User Location (GPS APIs) 🗺️

The Problem: You're building the next big thing in food delivery, and you need to show the user restaurants near their current location. Or perhaps a weather app that automatically shows the forecast for where they are. To do this, you need to tap into the device's GPS.

The Solution: Yet another fantastic library comes to our rescue! react-native-geolocation-service is a popular choice because it's actively maintained and provides more accurate location data on Android compared to the built-in React Native Geolocation API.

Getting Started with react-native-geolocation-service

Installation:

bash
# For npm users
npm install react-native-geolocation-service

# For yarn users
yarn add react-native-geolocation-service

And, of course, our good old friend, pod install for iOS:

bash
cd ios && pod install && cd ..

Configuration:

iOS (ios/YourProjectName/Info.plist):

You need to provide a reason for accessing the user's location.

xml
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to show you nearby restaurants.</string>

Android (android/app/src/main/AndroidManifest.xml):

xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Fetching the User's Location

Now, let's get the user's coordinates. Remember to request permission first!

javascript
import React, {useState, useEffect} from 'react';
import {View, Text, Button, Alert, Platform} from 'react-native';
import Geolocation from 'react-native-geolocation-service';
import {PERMISSIONS, request, check, RESULTS} from 'react-native-permissions';


const App = () => {
  const [location, setLocation] = useState(null);

  const requestLocationPermission = async () => {
    try {
      const platformPermission =
        Platform.OS === 'ios'
          ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
          : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION;

      const result = await request(platformPermission);

      if (result === RESULTS.GRANTED) {
        return true;
      }
      return false;
    } catch (err) {
      console.warn(err);
      return false;
    }
  };


  const getLocation = async () => {
    const hasPermission = await requestLocationPermission();
    if (!hasPermission) {
      Alert.alert('Error', 'Location permission denied');
      return;
    }

    Geolocation.getCurrentPosition(
      position => {
        setLocation(position);
      },
      error => {
        console.log(error.code, error.message);
        Alert.alert('Error', 'Could not get location');
      },
      {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
    );
  };

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Button title="Get My Location" onPress={getLocation} />
      {location && (
        <View style={{marginTop: 20}}>
          <Text>Latitude: {location.coords.latitude}</Text>
          <Text>Longitude: {location.coords.longitude}</Text>
        </View>
      )}
    </View>
  );
};

export default App;

Let's break it down:

  • We have a function requestLocationPermission that we call before trying to get the location.
  • Geolocation.getCurrentPosition is the star of the show.
  • It takes three arguments: a success callback, an error callback, and an options object.
  • In the success callback, we receive a position object which contains coords with the latitude and longitude.
  • The options object lets us fine-tune the location request. enableHighAccuracy: true will use the GPS for a more precise location.

Real-World Scenario: Imagine a ride-sharing app. It needs your precise location to send a car to you. That's a great example of where ACCESS_FINE_LOCATION and enableHighAccuracy are crucial. A weather app, on the other hand, might only need your general area, so it could potentially use a less precise (and less battery-intensive) method.


4. Adding Haptic Feedback & Vibrations 📳

The Problem: Your app feels a bit... lifeless. Users tap buttons, and things happen, but there's no physical acknowledgment. How can you make your app feel more responsive and engaging?

The Solution: Haptic feedback and vibrations! These subtle (or not-so-subtle) buzzes and taps can provide confirmation for actions, alert users, and generally make your app feel more polished and integrated with the device.

For this, we can use the library react-native-haptic-feedback.

Getting Started with react-native-haptic-feedback

Installation:

bash
# For npm users
npm install react-native-haptic-feedback

# For yarn users
yarn add react-native-haptic-feedback

And for iOS... you guessed it:

bash
cd ios && pod install && cd ..

This library generally doesn't require extra permissions, which is a nice bonus!

Triggering Haptic Feedback

Using this library is wonderfully simple.

javascript
import React from 'react';
import {View, Button, TouchableOpacity, Text, StyleSheet} from 'react-native';
import HapticFeedback from 'react-native-haptic-feedback';

const options = {
  enableVibrateFallback: true,
  ignoreAndroidSystemSettings: false,
};

const App = () => {
  return (
    <View style={styles.container}>
      <Button
        title="Trigger 'impactLight'"
        onPress={() => HapticFeedback.trigger('impactLight', options)}
      />
       <Button
        title="Trigger 'notificationSuccess'"
        onPress={() => HapticFeedback.trigger('notificationSuccess', options)}
      />
       <TouchableOpacity
        style={styles.customButton}
        onPress={() => HapticFeedback.trigger('impactHeavy', options)}
       >
         <Text style={styles.buttonText}>Heavy Impact</Text>
       </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'space-around',
        alignItems: 'center',
        padding: 20
    },
    customButton: {
        backgroundColor: '#4CAF50',
        padding: 15,
        borderRadius: 5
    },
    buttonText: {
        color: 'white',
        fontSize: 16
    }
})

export default App;

Explanation:

  • We import HapticFeedback from the library.
  • The trigger method is all you need. You pass it a string that represents the type of feedback you want.
  • Different types create different sensations. For example:
    • impactLight, impactMedium, impactHeavy: These are your general-purpose "taps."
    • notificationSuccess, notificationWarning, notificationError: These are great for providing feedback after an action, like a successful form submission or a failed login.
  • The options object allows for some configuration, like enabling a fallback to regular vibration if haptics aren't available.

A Touch of Humor: Think of haptic feedback as your app gently tapping the user on the shoulder to say "Hey, I got that!" versus vibration which is more like your app frantically shaking the user and screaming "PAY ATTENTION TO ME!" Use haptics for subtle cues and vibrations for important notifications.


Further Reading & Resources 📚

Challenge

Challenge: Build a Feature-Rich Profile Updater

Your task is to implement the logic for a React Native component, ProfileUpdater, that interacts with several native device APIs. You will need to correctly sequence permission checks, requests, and API calls for the camera/photo library and GPS, and provide haptic feedback for user actions.

Requirements:

  1. Create a React Functional Component: The component should be named ProfileUpdater.

  2. State Management:

    • Initialize and manage a state variable profileImageUri to hold the URI of the selected image.
    • Initialize and manage another state variable userLocation to store an object with latitude and longitude.
  3. Implement handleUpdateProfilePicture function:

    • This async function should handle the process of selecting a new profile picture.
    • First, check for the platform-specific camera permission (PERMISSIONS.IOS.CAMERA or PERMISSIONS.ANDROID.CAMERA).
    • If the permission is RESULTS.DENIED, request it.
    • If the permission is RESULTS.GRANTED, call launchImageLibrary().
    • On a successful image selection, update the profileImageUri state and trigger a notificationSuccess haptic feedback.
    • If permission is RESULTS.BLOCKED, log a message to the console.
  4. Implement handleFetchLocation function:

    • This async function should fetch the user's current GPS coordinates.
    • Check for the appropriate fine location permission (PERMISSIONS.IOS.LOCATION_WHEN_IN_USE or PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION).
    • If the permission status is not RESULTS.GRANTED, request it.
    • If permission is granted, call Geolocation.getCurrentPosition().
    • On success, update the userLocation state with the coordinates and trigger an impactLight haptic feedback.
    • On error, log the error message to the console.

Expected result

Your code should correctly implement the two handler functions to check and request permissions before accessing the native device features. The state should be updated accordingly, triggering UI changes and haptic feedback.

javascript
import React, { useState } from 'react';
import { View, Text, Button, Image, Platform } from 'react-native';
import * as Permissions from 'react-native-permissions';
import { launchImageLibrary } from 'react-native-image-picker';
import Geolocation from 'react-native-geolocation-service';
import HapticFeedback from 'react-native-haptic-feedback';

const { PERMISSIONS, RESULTS } = Permissions;

const ProfileUpdater = () => {
  const [profileImageUri, setProfileImageUri] = useState(null);
  const [userLocation, setUserLocation] = useState(null);

  const handleUpdateProfilePicture = async () => {
    const cameraPermission = Platform.OS === 'ios' ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA;
    let status = await Permissions.check(cameraPermission);

    if (status === RESULTS.DENIED) {
      status = await Permissions.request(cameraPermission);
    }

    if (status === RESULTS.GRANTED) {
      launchImageLibrary({ mediaType: 'photo' }, (response) => {
        if (!response.didCancel && response.assets && response.assets.length > 0) {
          setProfileImageUri(response.assets[0].uri);
          HapticFeedback.trigger('notificationSuccess', { enableVibrateFallback: true });
        }
      });
    } else if (status === RESULTS.BLOCKED) {
        console.log('Camera permission is blocked and cannot be requested.');
    }
  };

  const handleFetchLocation = async () => {
    const locationPermission = Platform.OS === 'ios'
      ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
      : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION;
    
    let status = await Permissions.check(locationPermission);

    if (status === RESULTS.DENIED) {
      status = await Permissions.request(locationPermission);
    }

    if (status === RESULTS.GRANTED) {
      Geolocation.getCurrentPosition(
        (position) => {
          setUserLocation({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          });
          HapticFeedback.trigger('impactLight', { enableVibrateFallback: true });
        },
        (error) => {
          console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
      );
    } else {
        console.log('Location permission not granted.');
    }
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      {profileImageUri && (
        <Image
          source={{ uri: profileImageUri }}
          style={{ width: 150, height: 150, borderRadius: 75, marginBottom: 20 }}
        />
      )}
      <Button
        title="Update Profile Picture"
        onPress={handleUpdateProfilePicture}
      />
      <View style={{ height: 20 }} />
      <Button
        title="Fetch My Location"
        onPress={handleFetchLocation}
      />
      {userLocation && (
        <Text style={{ marginTop: 20, fontSize: 16 }}>
          {`Latitude: ${userLocation.latitude}\nLongitude: ${userLocation.longitude}`}
        </Text>
      )}
    </View>
  );
};

export default ProfileUpdater;
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.