Skip to main content

Working with Device APIs

1. Using Geolocation API

Property Description Notes
getCurrentPosition Gets the device's current location Requires user permission
watchPosition Watches for location changes Continuously updates location
clearWatch Stops watching for location changes Accepts watch ID from watchPosition

Example: Get Current Location

import { Geolocation } from 'react-native';

const getLocation = async () => {
  try {
    const position = await Geolocation.getCurrentPosition(
      (location) => {
        console.log('Current location:', location);
      },
      (error) => {
        console.log('Error getting location:', error);
      },
      {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 60000,
      }
    );
  } catch (error) {
    console.log('Error:', error);
  }
};

Example: Watch Location Changes

import { Geolocation } from 'react-native';

const watchId = Geolocation.watchPosition(
  (location) => {
    console.log('Updated location:', location);
  },
  (error) => {
    console.log('Error watching location:', error);
  },
  {
    distanceFilter: 10,
    interval: 5000,
  }
);

// Stop watching when needed
// Geolocation.clearWatch(watchId);
Note: On iOS, you must add the NSLocationWhenInUseUsageDescription or NSLocationAlwaysAndWhenInUseUsageDescription key to your Info.plist for location permissions.
Warning: Always handle permission denial gracefully. Users may deny location access, which should not crash your app.

2. Accessing Camera Roll

Property Description Notes
CameraRoll.getPhotos() Fetches photos from the camera roll Requires permission to access media library
CameraRoll.saveToCameraRoll() Saves a photo or video to the camera roll Supports both image and video formats

Example: Fetching Photos

import { CameraRoll } from 'react-native';

const fetchPhotos = async () => {
  try {
    const photos = await CameraRoll.getPhotos({
      first: 10,
      assetType: 'Photos',
    });
    console.log(photos.edges);
  } catch (error) {
    console.error('Error fetching photos:', error);
  }
};

Example: Saving to Camera Roll

import { CameraRoll } from 'react-native';

const savePhoto = async () => {
  try {
    const imageUrl = 'https://example.com/photo.jpg';
    await CameraRoll.saveToCameraRoll(imageUrl, 'photo');
    console.log('Photo saved to camera roll');
  } catch (error) {
    console.error('Error saving photo:', error);
  }
};
Note: On iOS, you must add the NSPhotoLibraryUsageDescription key to your Info.plist for camera roll access.
Warning: On Android, ensure you have the WRITE_EXTERNAL_STORAGE permission declared in your AndroidManifest.xml.

3. Using Clipboard API

Method Description Notes
Clipboard.getString() Retrieves the current text from the clipboard Returns a Promise resolving to the clipboard content as a string
Clipboard.setString() Sets the clipboard content to a provided string Accepts a string value to be copied to the clipboard

Example: Reading from Clipboard

import Clipboard from '@react-native-clipboard/clipboard';

const readFromClipboard = async () => {
  const content = await Clipboard.getString();
  console.log('Clipboard content:', content);
};

readFromClipboard();

Example: Writing to Clipboard

import Clipboard from '@react-native-clipboard/clipboard';

const writeToClipboard = () => {
  Clipboard.setString('Hello, React Native!');
  console.log('Text copied to clipboard');
};

writeToClipboard();
Note: On iOS, the clipboard API is available only in apps that have the UIPasteboard entitlement. On Android, it works without additional setup.

4. Accessing Device Contacts

Property Description Platform Support
Contacts Module to access device contact list iOS / Android

Example: Fetching Contacts

import { PermissionsAndroid, Platform } from 'react-native';
import Contacts from 'react-native-contacts';

const fetchContacts = async () => {
  try {
    if (Platform.OS === 'android') {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
        {
          title: 'Contacts Permission',
          message: 'This app needs access to your contacts.',
        }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        const contacts = await Contacts.getAll();
        console.log(contacts);
      }
    } else {
      const contacts = await Contacts.getAll();
      console.log(contacts);
    }
  } catch (error) {
    console.error('Error fetching contacts:', error);
  }
};

Example: Contact Fields

const contactFields = [
  'givenName',
  'familyName',
  'phoneNumbers',
  'emailAddresses',
  'postalAddresses'
];

const contactWithFields = await Contacts.getContactById(contactId, contactFields);
Note: On iOS, you must add the NSContactsUsageDescription key to your Info.plist to request contact permissions.
Warning: Accessing contacts requires user permission and should be handled carefully to respect privacy.

5. Using Share API

Property Description Platform Support
Share.open() Opens the native sharing dialog with provided content iOS | Android
Share.isAvailable() Checks if sharing is available on the device iOS | Android

Example: Sharing Text Content

import Share from 'react-native-share';

const shareText = async () => {
  try {
    await Share.open({
      title: 'Share via',
      message: 'Check out this awesome app!',
      url: 'https://example.com',
    });
  } catch (error) {
    console.log(error);
  }
};

Example: Sharing a File

import Share from 'react-native-share';

const shareFile = async () => {
  try {
    await Share.open({
      title: 'Share File',
      url: 'file:///path/to/file.pdf',
      type: 'application/pdf',
    });
  } catch (error) {
    console.log(error);
  }
};
Note: On Android, the file URL must be accessible via a content URI or file path.
Warning: The Share API requires appropriate permissions and may not work in all environments (e.g., simulator).

6. Accessing Device Information

Property Description Platform Support
DeviceInfo Provides access to device-specific information such as model, brand, and system version. iOS | Android
DeviceInfo.getDeviceId() Returns a unique identifier for the device. iOS | Android
DeviceInfo.getModel() Retrieves the device model name (e.g., iPhone 14, Galaxy S21). iOS | Android
DeviceInfo.getBrand() Gets the brand of the device (e.g., Apple, Samsung). iOS | Android
DeviceInfo.getSystemVersion() Fetches the operating system version (e.g., 16.0, Android 12). iOS | Android
DeviceInfo.getDeviceType() Determines whether the device is a phone, tablet, or other type. iOS | Android

Example: Fetching Device Information

import DeviceInfo from 'react-native-device-info';

const deviceInfo = {
  model: DeviceInfo.getModel(),
  brand: DeviceInfo.getBrand(),
  systemVersion: DeviceInfo.getSystemVersion(),
  deviceId: DeviceInfo.getDeviceId(),
  deviceType: DeviceInfo.getDeviceType()
};

console.log(deviceInfo);
Note: On Android, getDeviceId() may return a hashed value for privacy reasons.

7. Implementing Biometric Authentication

Example: Basic Biometric Authentication Setup

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';

const BiometricAuth = () => {
  const handleBiometricAuth = async () => {
    const result = await request(PERMISSIONS.ANDROID.CAMERA, {
      title: 'Biometric Login',
      message: 'We use biometrics for secure login',
      buttonPositive: 'OK',
      buttonNegative: 'Cancel'
    });

    if (result === RESULTS.GRANTED) {
      console.log('Biometric access granted');
    } else {
      console.log('Biometric access denied');
    }
  };

  return (
    <View>
      <TouchableOpacity onPress={handleBiometricAuth}>
        <Text>Authenticate with Biometrics</Text>
      </TouchableOpacity>
    </View>
  );
};

export default BiometricAuth;
Permission Description Status
PERMISSIONS.ANDROID.CAMERA Required for biometric authentication on Android NEW
PERMISSIONS.IOS.FACE_ID Face ID permission on iOS devices DEPRECATED
Note: Ensure you have added the required permissions to your app's manifest files (AndroidManifest.xml for Android, Info.plist for iOS) before attempting biometric authentication.

8. Using App Settings

Setting Description Example Notes
permissions Controls access to device features like camera, location {camera: 'granted', location: 'denied'} Must request at runtime for sensitive permissions
notifications Manages push notification permissions and settings {enabled: true, sound: false} Requires user consent to enable
backgroundModes Enables app to run in background for specific tasks {location: true, audio: false} Must declare in app manifest

Example: Requesting Camera Permission

import { PermissionsAndroid, Platform } from 'react-native';

const requestCameraPermission = async () => {
  if (Platform.OS === 'android') {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'Camera Permission',
          message: 'App needs camera access to scan QR codes',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK'
        }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('Camera permission granted');
      } else {
        console.log('Camera permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  }
};

Example: Checking Notification Settings

import { PushNotificationIOS } from 'react-native';

const checkNotificationSettings = () => {
  PushNotificationIOS.getInitialNotification()
    .then(notification => {
      if (notification) {
        console.log('Initial notification:', notification);
      }
    })
    .catch(err => {
      console.error('Error checking notifications:', err);
    });
};
Note: On iOS, notification permissions must be requested through PushNotificationIOS and require the app to be registered for remote notifications.
Warning: Background modes can drain battery life significantly if not managed properly. Always check for permission and disable when not needed.

9. Checking Network Connectivity

Example: Basic Network Status Check

import { NetInfo } from &#x27;react-native&#x27;;

const checkNetworkStatus = async () => {
  const state = await NetInfo.fetch();
  console.log("Network type:", state.type);
  console.log("Is connected:", state.isConnected);
};

checkNetworkStatus();
Property Description Values
type Network type detected "none", "unknown", "cellular", "wifi", "bluetooth", "ethernet", "wimax", "vpn", "other"
isConnected Whether device has network access true, false
isInternetReachable Whether device can reach the internet true, false, null
Note: On iOS, isInternetReachable may return null if the device is connected to a network but cannot reach the internet.
Warning: The NetInfo API is deprecated in favor of the newer NetworkStatus from @react-native-community/netinfo.

Example: Using @react-native-community/netinfo

import NetInfo from &#x27;@react-native-community/netinfo&#x27;;

const handleConnectivityChange = (state) => {
  console.log("Network type:", state.type);
  console.log("Is connected:", state.isConnected);
  console.log("Is internet reachable:", state.isInternetReachable);
};

NetInfo.addEventListener(handleConnectivityChange);

10. Using Battery Status API

Property Description Values
level Battery level as a percentage 0-100
charging Indicates if the device is currently charging true or false
chargingTime Time in seconds until battery is fully charged number
dischargingTime Time in seconds until battery is fully discharged number

Example: Battery Status API Usage

import { Battery } from &#x27;react-native-battery&#x27;;

const getBatteryInfo = async () => {
  const batteryLevel = await Battery.getBatteryLevel();
  const isCharging = await Battery.isCharging();
  const chargingTime = await Battery.getChargingTime();
  const dischargingTime = await Battery.getDischargingTime();

  console.log(&#x27;Battery Level:&#x27;, batteryLevel);
  console.log(&#x27;Is Charging:&#x27;, isCharging);
  console.log(&#x27;Charging Time:&#x27;, chargingTime);
  console.log(&#x27;Discharging Time:&#x27;, dischargingTime);
};
Note: The react-native-battery package is required to access battery information. Ensure it's installed and linked properly.

Was this article helpful?