react-native-permissions

repository·master·Indexed 26 days ago

https://github.com/zoontek/react-native-permissions

A unified permissions API for React Native providing a consistent interface for requesting and checking permissions across iOS, Android, and Windows. Version 5.6.1 includes support for individual and multiple permission checks, notification-specific handling, and system settings navigation via openSettings(). It provides specialized configuration for iOS Podfiles, Android Manifests, and Expo config plugins.

Tokens
7.8K
Snippets
14
Records
39
Agent score
87%

What's inside react-native-permissions

  1. Manually link react-native-permissions on Android

    master

    To manually link on Android, follow these three steps:

    1. Update android/settings.gradle to include the project.
    2. Add the implementation dependency in android/app/build.gradle.
    3. Register the RNPermissionsPackage in MainApplication.java within the getPackages method.
    // 1. android/settings.gradle
    include ':react-native-permissions'
    project(':react-native-permissions').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-permissions/android')
    
    // 2. android/app/build.gradle
    dependencies {
      // ...
      implementation project(':react-native-permissions')
    }
    
    // 3. MainApplication.java
    import com.zoontek.rnpermissions.RNPermissionsPackage;
    
    // ... inside getPackages()
    packages.add(new RNPermissionsPackage());
  2. Understand the permission flow and logic

    master

    The library abstracts platform differences (iOS, Android, Windows) using a specific logic flow for check and request operations:

    Logic Flow

    1. check(PERMISSIONS.X.Y):

      • If the feature is unavailable on the device $\rightarrow$ RESULTS.UNAVAILABLE.
      • If permission is already granted $\rightarrow$ RESULTS.GRANTED or RESULTS.LIMITED.
      • If permission is not granted:
        • If not requestable (or not Android) $\rightarrow$ RESULTS.BLOCKED.
        • If requestable $\rightarrow$ RESULTS.DENIED.
    2. request(PERMISSIONS.X.Y):

      • If the user accepts $\rightarrow$ RESULTS.GRANTED or RESULTS.LIMITED.
      • If the user denies or the permission is no longer requestable $\rightarrow$ RESULTS.BLOCKED.
    • Check status: Use check first.
    • If granted: Proceed with the feature.
    • If blocked: Prompt the user to open system settings using openSettings (Note: openSettings does not show on Android).
    • If denied: Show a UI element (like a button) to trigger request.
    • After request: If the result is blocked, prompt the user to go to settings via openSettings.
  3. Configure iOS Setup

    master

    By default, no permissions are available on iOS. You must configure your Podfile to include the required permissions and update your Info.plist with usage descriptions.

    1. Update Podfile: Define a node_require helper to resolve scripts and call setup_permissions with an array of the specific permissions your app requires.
    2. Install Pods: Run pod install in your ios directory. Note: You must re-execute this command every time you update the setup_permissions configuration.
    3. Update Info.plist: Add the corresponding usage description keys (e.g., NSCameraUsageDescription) for every permission specified in your Podfile.
    # In your Podfile
    def node_require(script)
      require Pod::Executable.execute_command('node', ['-p',
        "require.resolve('
          '#{script}',
          {paths: [process.argv[1]]},
        )", __dir__]).strip
    end
    
    node_require('react-native/scripts/react_native_pods.rb')
    node_require('react-native-permissions/scripts/setup.rb')
    
    setup_permissions([
      'Camera',
      'Microphone',
    ])
  4. Manually link react-native-permissions on Windows

    master

    For Windows integration, follow these steps in Visual Studio:

    1. Add Project: Open windows/myapp.sln, right-click the Solution icon, select Add > Existing Project, and choose node_modules\react-native-permissions\windows\RNPermissions\RNPermissions.vcxproj.
    2. Add Reference: In windows/myapp/myapp.vcxproj, right-click the main application project, select Add > Reference..., and check RNPermissions.
    3. Include Header: Add #include "winrt/RNPermissions.h" to your pch.h file.
    4. Register Provider: In app.cpp, add PackageProviders().Append(winrt::RNPermissions::ReactPackageProvider()); before the InitializeComponent(); call.
  5. Configure Expo Setup

    master

    If using Expo, do not follow the standard iOS/Android manual setup steps. Instead, update your Expo configuration (app.config.js or app.json) using the react-native-permissions plugin.

    • For Dynamic Config (app.config.js/ts): Import permissions from react-native-permissions/expo and add it to the plugins array. Specify iosPermissions and android.permissions.
    • For Static Config (app.json): Add react-native-permissions to the plugins array.
    • Note: You still need to perform the iOS Podfile setup (steps 1-3 in the iOS section) and add infoPlist descriptions.
    // app.config.ts example
    import permissions from 'react-native-permissions/expo';
    
    export default {
      plugins: [
        permissions({
          iosPermissions: ['Camera', 'Microphone'],
        }),
      ],
      ios: {
        infoPlist: {
          NSCameraUsageDescription: '[REASON]',
          NSMicrophoneUsageDescription: '[REASON]',
        },
      },
      android: {
        permissions: ['android.permission.CAMERA', 'android.permission.RECORD_AUDIO'],
      },
    };
  6. Configure Android Setup

    master

    To enable permissions on Android, add the desired <uses-permission> tags to your android/app/src/main/AndroidManifest.xml file. Only include the permissions that your application actually uses.

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
      <!-- Add permissions here -->
      <uses-permission android:name="android.permission.CAMERA" />
      <uses-permission android:name="android.permission.RECORD_AUDIO" />
    </manifest>
  7. Mock permissions for Jest testing

    master

    To test permission logic in Jest, add the following to your jest.setup.js file to mock the native module:

    jest.mock('react-native-permissions', () => require('react-native-permissions/mock'));

    Ensure your Jest configuration includes the setup file:

    setupFiles: ['<rootDir>/jest.setup.js'];
  8. Configure iOS permissions via setup.rb

    master

    To enable specific permissions in your iOS project, you must use the setup_permissions function within your Podfile. This script automates the configuration of the RNPermissions.podspec by updating s.source_files and s.frameworks based on the permissions you explicitly request.

    To use it, call setup_permissions and pass an array of permission names that correspond to the directory names in the ios/ folder of the package.

    Available Permission Keys:

    • AppTrackingTransparency
    • Bluetooth
    • Calendars
    • CalendarsWriteOnly
    • Camera
    • Contacts
    • FaceID
    • LocationAccuracy
    • LocationAlways
    • LocationWhenInUse
    • MediaLibrary
    • Microphone
    • Motion
    • Notifications
    • PhotoLibrary
    • PhotoLibraryAddOnly
    • Reminders
    • Siri
    • SpeechRecognition
    • StoreKit
  9. Use the Expo config plugin with `withPermissions`

    master
    To integrate react-native-permissions with an Expo project, use the withPermissions config plugin. This plugin allows you to configure the necessary native permissions (such as AppTrackingTransparency, Bluetooth, Calendars, etc.) within your app.json or app.config.js during the prebuild process.