Git Product home page Git Product logo

react-native-permissions's Introduction

☝🏼 react-native-permissions

An unified permissions API for React Native on iOS, Android and Windows.
(For Windows only builds 18362 and later are supported)

mit licence npm version npm downloads
platform - android platform - ios platform - windows

Support

This library follows the React Native releases support policy.
It is supporting the latest version, and the two previous minor series.

Setup

$ npm install --save react-native-permissions
# --- or ---
$ yarn add react-native-permissions

iOS

  1. By default, no permissions are setuped. So first, require the setup script in your Podfile:
# with react-native >= 0.72
- # Resolve react_native_pods.rb with node to allow for hoisting
- require Pod::Executable.execute_command('node', ['-p',
-   'require.resolve(
-     "react-native/scripts/react_native_pods.rb",
-     {paths: [process.argv[1]]},
-   )', __dir__]).strip

+ def node_require(script)
+   # Resolve script with node to allow for hoisting
+   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')
# with react-native < 0.72
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
+ require_relative '../node_modules/react-native-permissions/scripts/setup'
  1. Then in the same file, add a setup_permissions call with the wanted permissions:
# …

platform :ios, min_ios_version_supported
prepare_react_native_project!

# ⬇️ uncomment wanted permissions
setup_permissions([
  # 'AppTrackingTransparency',
  # 'Bluetooth',
  # 'Calendars',
  # 'CalendarsWriteOnly',
  # 'Camera',
  # 'Contacts',
  # 'FaceID',
  # 'LocationAccuracy',
  # 'LocationAlways',
  # 'LocationWhenInUse',
  # 'MediaLibrary',
  # 'Microphone',
  # 'Motion',
  # 'Notifications',
  # 'PhotoLibrary',
  # 'PhotoLibraryAddOnly',
  # 'Reminders',
  # 'Siri',
  # 'SpeechRecognition',
  # 'StoreKit',
])

# …
  1. Then execute pod install (πŸ“ŒΒ Β Note that it must be re-executed each time you update this config).
  2. Finally, update your Info.plist with the wanted permissions usage descriptions:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>

  <!-- 🚨 Keep only the permissions used in your app 🚨 -->

  <key>NSAppleMusicUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSBluetoothAlwaysUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSBluetoothPeripheralUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSCalendarsFullAccessUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSCalendarsWriteOnlyAccessUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSCameraUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSContactsUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSFaceIDUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSLocationTemporaryUsageDescriptionDictionary</key>
  <dict>
    <key>YOUR-PURPOSE-KEY</key>
    <string>YOUR TEXT</string>
  </dict>
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSMicrophoneUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSMotionUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSPhotoLibraryUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSPhotoLibraryAddUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSRemindersFullAccessUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSSpeechRecognitionUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSSiriUsageDescription</key>
  <string>YOUR TEXT</string>
  <key>NSUserTrackingUsageDescription</key>
  <string>YOUR TEXT</string>

  <!-- … -->

</dict>
</plist>
🧩 For expo users, see the plugin instructions

Add wanted permissions (see step 1) to the plugin config:

{
  "name": "My awesome app",
  "plugins": [
    [
      "react-native-permissions",
      {
        "iosPermissions": [
          "AppTrackingTransparency",
          "Bluetooth",
          "CalendarsWriteOnly",
          "Notifications",
          "SpeechRecognition"
        ]
      }
    ]
  ]
}

Android

Add all wanted permissions to your app android/app/src/main/AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

  <!-- 🚨 Keep only the permissions used in your app 🚨 -->

  <uses-permission android:name="android.permission.ACCEPT_HANDOVER" />
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
  <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
  <uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL" />
  <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
  <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
  <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
  <uses-permission android:name="android.permission.BODY_SENSORS" />
  <uses-permission android:name="android.permission.BODY_SENSORS_BACKGROUND" />
  <uses-permission android:name="android.permission.CALL_PHONE" />
  <uses-permission android:name="android.permission.CAMERA" />
  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" />
  <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
  <uses-permission android:name="android.permission.READ_CALENDAR" />
  <uses-permission android:name="android.permission.READ_CALL_LOG" />
  <uses-permission android:name="android.permission.READ_CONTACTS" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
  <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
  <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
  <uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
  <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
  <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  <uses-permission android:name="android.permission.READ_SMS" />
  <uses-permission android:name="android.permission.RECEIVE_MMS" />
  <uses-permission android:name="android.permission.RECEIVE_SMS" />
  <uses-permission android:name="android.permission.RECEIVE_WAP_PUSH" />
  <uses-permission android:name="android.permission.RECORD_AUDIO" />
  <uses-permission android:name="android.permission.SEND_SMS" />
  <uses-permission android:name="android.permission.USE_SIP" />
  <uses-permission android:name="android.permission.UWB_RANGING" />
  <uses-permission android:name="android.permission.WRITE_CALENDAR" />
  <uses-permission android:name="android.permission.WRITE_CALL_LOG" />
  <uses-permission android:name="android.permission.WRITE_CONTACTS" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  <!-- … -->

</manifest>

Windows

Open the project solution file from the windows folder. In the app project open Package.appxmanifest file. From there you can select which capabilites you want your app to support.

πŸ†˜ Manual linking

Because this package targets recent React Native versions, you probably don't need to link it manually. But if you have a special case, follow these additional instructions:

πŸ‘€ See manual linking instructions

iOS

Add this line to your ios/Podfile file, then run pod install.

target 'YourAwesomeProject' do
  # …
  pod 'RNPermissions', :path => '../node_modules/react-native-permissions'
end

Android

  1. Add the following lines to android/settings.gradle:
include ':react-native-permissions'
project(':react-native-permissions').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-permissions/android')
  1. Add the implementation line to the dependencies in android/app/build.gradle:
dependencies {
  // ...
  implementation project(':react-native-permissions')
}
  1. Add the import and link the package in MainApplication.java:
import com.zoontek.rnpermissions.RNPermissionsPackage; // <- add the RNPermissionsPackage import

public class MainApplication extends Application implements ReactApplication {

  // …

  @Override
  protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    // …
    packages.add(new RNPermissionsPackage());
    return packages;
  }

  // …
}

Windows

  1. In windows/myapp.sln add the RNCConfig project to your solution:
  • Open the solution in Visual Studio 2019
  • Right-click Solution icon in Solution Explorer > Add > Existing Project
  • Select node_modules\react-native-permissions\windows\RNPermissions\RNPermissions.vcxproj
  1. In windows/myapp/myapp.vcxproj ad a reference to RNPermissions to your main application project. From Visual Studio 2019:
  • Right-click main application project > Add > Reference...
  • Check RNPermissions from Solution Projects.
  1. In pch.h add #include "winrt/RNPermissions.h".

  2. In app.cpp add PackageProviders().Append(winrt::RNPermissions::ReactPackageProvider()); before InitializeComponent();.

Understanding permission flow

As permissions are not handled in the same way on iOS and Android, this library provides an abstraction over the two platforms' behaviors. To understand it a little better, take a look to these two flowcharts:

iOS flow

   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
   ┃ check(PERMISSIONS.IOS.CAMERA) ┃
   ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                   β”‚
       Is the feature available
           on this deviceΒ ?
                   β”‚           ╔════╗
                   β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                   β”‚           β•šβ•β•β•β•β•              β”‚
                ╔═════╗                            β–Ό
                β•‘ YES β•‘                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β•šβ•β•β•β•β•β•                 β”‚ RESULTS.UNAVAILABLE β”‚
                   β”‚                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           Is the permission
             requestableΒ ?
                   β”‚           ╔════╗
                   β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                   β”‚           β•šβ•β•β•β•β•              β”‚
                ╔═════╗                            β–Ό
                β•‘ YES β•‘                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β•šβ•β•β•β•β•β•                  β”‚ RESULTS.BLOCKED / β”‚
                   β”‚                     β”‚ RESULTS.LIMITED / β”‚
                   β”‚                     β”‚  RESULTS.GRANTED  β”‚
                   β–Ό                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚ RESULTS.DENIED β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
                   β–Ό
  ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
  ┃ request(PERMISSIONS.IOS.CAMERA) ┃
  ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                   β”‚
         Does the user accept
            the requestΒ ?
                   β”‚           ╔════╗
                   β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                   β”‚           β•šβ•β•β•β•β•              β”‚
                ╔═════╗                            β–Ό
                β•‘ YES β•‘                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β•šβ•β•β•β•β•β•                   β”‚ RESULTS.BLOCKED β”‚
                   β”‚                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β–Ό
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚ RESULTS.GRANTED β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Android flow

 ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
 ┃ check(PERMISSIONS.ANDROID.CAMERA) ┃
 ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                   β”‚
       Is the feature available
           on this deviceΒ ?
                   β”‚           ╔════╗
                   β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                   β”‚           β•šβ•β•β•β•β•              β”‚
                ╔═════╗                            β–Ό
                β•‘ YES β•‘                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β•šβ•β•β•β•β•β•                 β”‚ RESULTS.UNAVAILABLE β”‚
                   β”‚                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           Is the permission
           already granted ?
                   β”‚           ╔═════╗
                   β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ YES ║─────────────┐
                   β”‚           β•šβ•β•β•β•β•β•             β”‚
                ╔════╗                             β–Ό
                β•‘ NO β•‘                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β•šβ•β•β•β•β•                   β”‚  RESULTS.GRANTED  β”‚
                   β”‚                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β–Ό
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚ RESULTS.DENIED │◀──────────────────────┐
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                       β”‚
                   β”‚                               β”‚
                   β–Ό                               β”‚
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓         ╔═════╗
┃ request(PERMISSIONS.ANDROID.CAMERA) ┃         β•‘ YES β•‘
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛         β•šβ•β•β•β•β•β•
                   β”‚                               β”‚
         Does the user accept                      β”‚
            the requestΒ ?                          β”‚
                   β”‚           ╔════╗      Is the permission
                   β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──── still requestableΒ ?
                   β”‚           β•šβ•β•β•β•β•              β”‚
                ╔═════╗                         ╔════╗
                β•‘ YES β•‘                         β•‘ NO β•‘
                β•šβ•β•β•β•β•β•                         β•šβ•β•β•β•β•
                   β”‚                               β”‚
                   β–Ό                               β–Ό
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚ RESULTS.GRANTED β”‚             β”‚ RESULTS.BLOCKED β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜             β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Windows flow

   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
   ┃ check(PERMISSIONS.WINDOWS.WEBCAM) ┃
   ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                     β”‚
         Is the feature available
              on this deviceΒ ?
                     β”‚           ╔════╗
                     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                     β”‚           β•šβ•β•β•β•β•              β”‚
                  ╔═════╗                            β–Ό
                  β•‘ YES β•‘                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β•šβ•β•β•β•β•β•                 β”‚ RESULTS.UNAVAILABLE β”‚
                     β”‚                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             Is the permission
               requestableΒ ?
                     β”‚           ╔════╗
                     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                     β”‚           β•šβ•β•β•β•β•              β”‚
                  ╔═════╗                            β–Ό
                  β•‘ YES β•‘                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β•šβ•β•β•β•β•β•                  β”‚ RESULTS.BLOCKED / β”‚
                     β”‚                     β”‚  RESULTS.GRANTED  β”‚
                     β–Ό                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚ RESULTS.DENIED β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚
                     β–Ό
  ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
  ┃ request(PERMISSIONS.WINDOWS.WEBCAM) ┃
  ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
                     β”‚
           Does the user accept
              the requestΒ ?
                     β”‚           ╔════╗
                     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•‘ NO ║──────────────┐
                     β”‚           β•šβ•β•β•β•β•              β”‚
                  ╔═════╗                            β–Ό
                  β•‘ YES β•‘                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β•šβ•β•β•β•β•β•                   β”‚ RESULTS.BLOCKED β”‚
                     β”‚                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β–Ό
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚ RESULTS.GRANTED β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

API

Supported permissions

Android permissions
import {PERMISSIONS} from 'react-native-permissions';

PERMISSIONS.ANDROID.ACCEPT_HANDOVER;
PERMISSIONS.ANDROID.ACCESS_BACKGROUND_LOCATION;
PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION;
PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION;
PERMISSIONS.ANDROID.ACCESS_MEDIA_LOCATION;
PERMISSIONS.ANDROID.ACTIVITY_RECOGNITION;
PERMISSIONS.ANDROID.ADD_VOICEMAIL;
PERMISSIONS.ANDROID.ANSWER_PHONE_CALLS;
PERMISSIONS.ANDROID.BLUETOOTH_ADVERTISE;
PERMISSIONS.ANDROID.BLUETOOTH_CONNECT;
PERMISSIONS.ANDROID.BLUETOOTH_SCAN;
PERMISSIONS.ANDROID.BODY_SENSORS;
PERMISSIONS.ANDROID.BODY_SENSORS_BACKGROUND;
PERMISSIONS.ANDROID.CALL_PHONE;
PERMISSIONS.ANDROID.CAMERA;
PERMISSIONS.ANDROID.GET_ACCOUNTS;
PERMISSIONS.ANDROID.NEARBY_WIFI_DEVICES;
PERMISSIONS.ANDROID.POST_NOTIFICATIONS;
PERMISSIONS.ANDROID.PROCESS_OUTGOING_CALLS;
PERMISSIONS.ANDROID.READ_CALENDAR;
PERMISSIONS.ANDROID.READ_CALL_LOG;
PERMISSIONS.ANDROID.READ_CONTACTS;
PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE;
PERMISSIONS.ANDROID.READ_MEDIA_AUDIO;
PERMISSIONS.ANDROID.READ_MEDIA_IMAGES;
PERMISSIONS.ANDROID.READ_MEDIA_VIDEO;
PERMISSIONS.ANDROID.READ_MEDIA_VISUAL_USER_SELECTED;
PERMISSIONS.ANDROID.READ_PHONE_NUMBERS;
PERMISSIONS.ANDROID.READ_PHONE_STATE;
PERMISSIONS.ANDROID.READ_SMS;
PERMISSIONS.ANDROID.RECEIVE_MMS;
PERMISSIONS.ANDROID.RECEIVE_SMS;
PERMISSIONS.ANDROID.RECEIVE_WAP_PUSH;
PERMISSIONS.ANDROID.RECORD_AUDIO;
PERMISSIONS.ANDROID.SEND_SMS;
PERMISSIONS.ANDROID.USE_SIP;
PERMISSIONS.ANDROID.UWB_RANGING;
PERMISSIONS.ANDROID.WRITE_CALENDAR;
PERMISSIONS.ANDROID.WRITE_CALL_LOG;
PERMISSIONS.ANDROID.WRITE_CONTACTS;
PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE;
iOS permissions
import {PERMISSIONS} from 'react-native-permissions';

PERMISSIONS.IOS.APP_TRACKING_TRANSPARENCY;
PERMISSIONS.IOS.BLUETOOTH;
PERMISSIONS.IOS.CALENDARS;
PERMISSIONS.IOS.CALENDARS_WRITE_ONLY;
PERMISSIONS.IOS.CAMERA;
PERMISSIONS.IOS.CONTACTS;
PERMISSIONS.IOS.FACE_ID;
PERMISSIONS.IOS.LOCATION_ALWAYS;
PERMISSIONS.IOS.LOCATION_WHEN_IN_USE;
PERMISSIONS.IOS.MEDIA_LIBRARY;
PERMISSIONS.IOS.MICROPHONE;
PERMISSIONS.IOS.MOTION;
PERMISSIONS.IOS.PHOTO_LIBRARY;
PERMISSIONS.IOS.PHOTO_LIBRARY_ADD_ONLY;
PERMISSIONS.IOS.REMINDERS;
PERMISSIONS.IOS.SIRI;
PERMISSIONS.IOS.SPEECH_RECOGNITION;
PERMISSIONS.IOS.STOREKIT;
Windows permissions
import {PERMISSIONS} from 'react-native-permissions';

PERMISSIONS.WINDOWS.ACCESSORY_MANAGER;
PERMISSIONS.WINDOWS.ACTIVITY;
PERMISSIONS.WINDOWS.ALLOW_ELEVATION;
PERMISSIONS.WINDOWS.ALL_APP_MODS;
PERMISSIONS.WINDOWS.ALL_JOYN;
PERMISSIONS.WINDOWS.APPOINTMENTS;
PERMISSIONS.WINDOWS.APPOINTMENTS_SYSTEM;
PERMISSIONS.WINDOWS.APP_BROADCAST_SERVICES;
PERMISSIONS.WINDOWS.APP_CAPTURE_SERVICES;
PERMISSIONS.WINDOWS.APP_CAPTURE_SETTINGS;
PERMISSIONS.WINDOWS.APP_DIAGNOSTICS;
PERMISSIONS.WINDOWS.APP_LICENSING;
PERMISSIONS.WINDOWS.AUDIO_DEVICE_CONFIGURATION;
PERMISSIONS.WINDOWS.BACKGROUND_MEDIA_PLAYBACK;
PERMISSIONS.WINDOWS.BACKGROUND_MEDIA_RECORDING;
PERMISSIONS.WINDOWS.BACKGROUND_SPATIAL_PERCEPTION;
PERMISSIONS.WINDOWS.BACKGROUND_VOIP;
PERMISSIONS.WINDOWS.BLOCKED_CHAT_MESSAGES;
PERMISSIONS.WINDOWS.BLUETOOTH;
PERMISSIONS.WINDOWS.BROAD_FILE_SYSTEM_ACCESS;
PERMISSIONS.WINDOWS.CAMERA_PROCESSING_EXTENSION;
PERMISSIONS.WINDOWS.CELLULAR_DEVICE_CONTROL;
PERMISSIONS.WINDOWS.CELLULAR_DEVICE_IDENTITY;
PERMISSIONS.WINDOWS.CELLULAR_MESSAGING;
PERMISSIONS.WINDOWS.CHAT_SYSTEM;
PERMISSIONS.WINDOWS.CODE_GENERATION;
PERMISSIONS.WINDOWS.CONFIRM_APP_CLOSE;
PERMISSIONS.WINDOWS.CONTACTS;
PERMISSIONS.WINDOWS.CONTACTS_SYSTEM;
PERMISSIONS.WINDOWS.CORTANA_PERMISSIONS;
PERMISSIONS.WINDOWS.CORTANA_SPEECH_ACCESSORY;
PERMISSIONS.WINDOWS.CUSTOM_INSTALL_ACTIONS;
PERMISSIONS.WINDOWS.DEVELOPMENT_MODE_NETWORK;
PERMISSIONS.WINDOWS.DEVICE_MANAGEMENT_DM_ACCOUNT;
PERMISSIONS.WINDOWS.DEVICE_MANAGEMENT_EMAIL_ACCOUNT;
PERMISSIONS.WINDOWS.DEVICE_MANAGEMENT_FOUNDATION;
PERMISSIONS.WINDOWS.DEVICE_MANAGEMENT_WAP_SECURITY_POLICIES;
PERMISSIONS.WINDOWS.DEVICE_PORTAL_PROVIDER;
PERMISSIONS.WINDOWS.DEVICE_UNLOCK;
PERMISSIONS.WINDOWS.DOCUMENTS_LIBRARY;
PERMISSIONS.WINDOWS.DUAL_SIM_TILES;
PERMISSIONS.WINDOWS.EMAIL;
PERMISSIONS.WINDOWS.EMAIL_SYSTEM;
PERMISSIONS.WINDOWS.ENTERPRISE_AUTHENTICATION;
PERMISSIONS.WINDOWS.ENTERPRISE_CLOUD_S_S_O;
PERMISSIONS.WINDOWS.ENTERPRISE_DATA_POLICY;
PERMISSIONS.WINDOWS.ENTERPRISE_DEVICE_LOCKDOWN;
PERMISSIONS.WINDOWS.EXPANDED_RESOURCES;
PERMISSIONS.WINDOWS.EXTENDED_BACKGROUND_TASK_TIME;
PERMISSIONS.WINDOWS.EXTENDED_EXECUTION_BACKGROUND_AUDIO;
PERMISSIONS.WINDOWS.EXTENDED_EXECUTION_CRITICAL;
PERMISSIONS.WINDOWS.EXTENDED_EXECUTION_UNCONSTRAINED;
PERMISSIONS.WINDOWS.FIRST_SIGN_IN_SETTINGS;
PERMISSIONS.WINDOWS.GAME_BAR_SERVICES;
PERMISSIONS.WINDOWS.GAME_LIST;
PERMISSIONS.WINDOWS.GAME_MONITOR;
PERMISSIONS.WINDOWS.GAZE_INPUT;
PERMISSIONS.WINDOWS.GLOBAL_MEDIA_CONTROL;
PERMISSIONS.WINDOWS.HUMANINTERFACEDEVICE;
PERMISSIONS.WINDOWS.INPUT_FOREGROUND_OBSERVATION;
PERMISSIONS.WINDOWS.INPUT_INJECTION_BROKERED;
PERMISSIONS.WINDOWS.INPUT_OBSERVATION;
PERMISSIONS.WINDOWS.INPUT_SUPPRESSION;
PERMISSIONS.WINDOWS.INTERNET_CLIENT;
PERMISSIONS.WINDOWS.INTERNET_CLIENT_SERVER;
PERMISSIONS.WINDOWS.INTEROP_SERVICES;
PERMISSIONS.WINDOWS.IOT;
PERMISSIONS.WINDOWS.LOCAL_SYSTEM_SERVICES;
PERMISSIONS.WINDOWS.LOCATION;
PERMISSIONS.WINDOWS.LOCATION_HISTORY;
PERMISSIONS.WINDOWS.LOCATION_SYSTEM;
PERMISSIONS.WINDOWS.LOW_LEVEL;
PERMISSIONS.WINDOWS.LOW_LEVEL_DEVICES;
PERMISSIONS.WINDOWS.MICROPHONE;
PERMISSIONS.WINDOWS.MOBILE;
PERMISSIONS.WINDOWS.MODIFIABLE_APP;
PERMISSIONS.WINDOWS.MUSIC_LIBRARY;
PERMISSIONS.WINDOWS.NETWORKING_VPN_PROVIDER;
PERMISSIONS.WINDOWS.NETWORK_CONNECTION_MANAGER_PROVISIONING;
PERMISSIONS.WINDOWS.NETWORK_DATA_PLAN_PROVISIONING;
PERMISSIONS.WINDOWS.NETWORK_DATA_USAGE_MANAGEMENT;
PERMISSIONS.WINDOWS.OEM_DEPLOYMENT;
PERMISSIONS.WINDOWS.OEM_PUBLIC_DIRECTORY;
PERMISSIONS.WINDOWS.ONE_PROCESS_VOIP;
PERMISSIONS.WINDOWS.OPTICAL;
PERMISSIONS.WINDOWS.PACKAGED_SERVICES;
PERMISSIONS.WINDOWS.PACKAGES_SERVICES;
PERMISSIONS.WINDOWS.PACKAGE_MANAGEMENT;
PERMISSIONS.WINDOWS.PACKAGE_POLICY_SYSTEM;
PERMISSIONS.WINDOWS.PACKAGE_QUERY;
PERMISSIONS.WINDOWS.PACKAGE_WRITE_REDIRECTION_COMPATIBILITY_SHIM;
PERMISSIONS.WINDOWS.PHONE_CALL;
PERMISSIONS.WINDOWS.PHONE_CALL_HISTORY;
PERMISSIONS.WINDOWS.PHONE_CALL_HISTORY_SYSTEM;
PERMISSIONS.WINDOWS.PHONE_LINE_TRANSPORT_MANAGEMENT;
PERMISSIONS.WINDOWS.PICTURES_LIBRARY;
PERMISSIONS.WINDOWS.POINT_OF_SERVICE;
PERMISSIONS.WINDOWS.PREVIEW_INK_WORKSPACE;
PERMISSIONS.WINDOWS.PREVIEW_PEN_WORKSPACE;
PERMISSIONS.WINDOWS.PREVIEW_STORE;
PERMISSIONS.WINDOWS.PREVIEW_UI_COMPOSITION;
PERMISSIONS.WINDOWS.PRIVATE_NETWORK_CLIENT_SERVER;
PERMISSIONS.WINDOWS.PROTECTED_APP;
PERMISSIONS.WINDOWS.PROXIMITY;
PERMISSIONS.WINDOWS.RADIOS;
PERMISSIONS.WINDOWS.RECORDED_CALLS_FOLDER;
PERMISSIONS.WINDOWS.REMOTE_PASSPORT_AUTHENTICATION;
PERMISSIONS.WINDOWS.REMOTE_SYSTEM;
PERMISSIONS.WINDOWS.REMOVABLE_STORAGE;
PERMISSIONS.WINDOWS.RESCAP;
PERMISSIONS.WINDOWS.RUN_FULL_TRUST;
PERMISSIONS.WINDOWS.SCREEN_DUPLICATION;
PERMISSIONS.WINDOWS.SECONDARY_AUTHENTICATION_FACTOR;
PERMISSIONS.WINDOWS.SECURE_ASSESSMENT;
PERMISSIONS.WINDOWS.SERIALCOMMUNICATION;
PERMISSIONS.WINDOWS.SHARED_USER_CERTIFICATES;
PERMISSIONS.WINDOWS.SLAPI_QUERY_LICENSE_VALUE;
PERMISSIONS.WINDOWS.SMBIOS;
PERMISSIONS.WINDOWS.SMS_SEND;
PERMISSIONS.WINDOWS.SPATIAL_PERCEPTION;
PERMISSIONS.WINDOWS.START_SCREEN_MANAGEMENT;
PERMISSIONS.WINDOWS.STORE_LICENSE_MANAGEMENT;
PERMISSIONS.WINDOWS.SYSTEM_MANAGEMENT;
PERMISSIONS.WINDOWS.TARGETED_CONTENT;
PERMISSIONS.WINDOWS.TEAM_EDITION_DEVICE_CREDENTIAL;
PERMISSIONS.WINDOWS.TEAM_EDITION_EXPERIENCE;
PERMISSIONS.WINDOWS.TEAM_EDITION_VIEW;
PERMISSIONS.WINDOWS.UAP;
PERMISSIONS.WINDOWS.UI_AUTOMATION;
PERMISSIONS.WINDOWS.UNVIRTUALIZED_RESOURCES;
PERMISSIONS.WINDOWS.USB;
PERMISSIONS.WINDOWS.USER_ACCOUNT_INFORMATION;
PERMISSIONS.WINDOWS.USER_DATA_ACCOUNTS_PROVIDER;
PERMISSIONS.WINDOWS.USER_DATA_SYSTEM;
PERMISSIONS.WINDOWS.USER_PRINCIPAL_NAME;
PERMISSIONS.WINDOWS.USER_SYSTEM_ID;
PERMISSIONS.WINDOWS.VIDEOS_LIBRARY;
PERMISSIONS.WINDOWS.VOIP_CALL;
PERMISSIONS.WINDOWS.WALLET_SYSTEM;
PERMISSIONS.WINDOWS.WEBCAM;
PERMISSIONS.WINDOWS.WIFI_CONTROL;
PERMISSIONS.WINDOWS.XBOX_ACCESSORY_MANAGEMENT;

Permissions statuses

Permission checks and requests resolve into one of these statuses:

Return value Notes
RESULTS.UNAVAILABLE This feature is not available (on this device / in this context)
RESULTS.DENIED The permission has not been requested / is denied but requestable
RESULTS.GRANTED The permission is granted
RESULTS.LIMITED The permission is granted but with limitations
RESULTS.BLOCKED The permission is denied and not requestable anymore

Methods

// type used in usage examples
type PermissionStatus = 'unavailable' | 'denied' | 'limited' | 'granted' | 'blocked';

check

Check one permission status.

⚠️  Android will never return blocked on check, you have to call request to get the info.

function check(permission: string): Promise<PermissionStatus>;
import {check, PERMISSIONS, RESULTS} from 'react-native-permissions';

check(PERMISSIONS.IOS.LOCATION_ALWAYS)
  .then((result) => {
    switch (result) {
      case RESULTS.UNAVAILABLE:
        console.log('This feature is not available (on this device / in this context)');
        break;
      case RESULTS.DENIED:
        console.log('The permission has not been requested / is denied but requestable');
        break;
      case RESULTS.LIMITED:
        console.log('The permission is limited: some actions are possible');
        break;
      case RESULTS.GRANTED:
        console.log('The permission is granted');
        break;
      case RESULTS.BLOCKED:
        console.log('The permission is denied and not requestable anymore');
        break;
    }
  })
  .catch((error) => {
    // …
  });

request

Request one permission.

The rationale is only available and used on Android. It can be a native alert (a Rationale object) or a custom implementation (that resolves with a boolean).

type Rationale = {
  title: string;
  message: string;
  buttonPositive?: string;
  buttonNegative?: string;
  buttonNeutral?: string;
};

function request(
  permission: string,
  rationale?: Rationale | (() => Promise<boolean>),
): Promise<PermissionStatus>;
import {request, PERMISSIONS} from 'react-native-permissions';

request(PERMISSIONS.IOS.LOCATION_ALWAYS).then((result) => {
  // …
});

checkNotifications

Check notifications permission status and get notifications settings values.

type NotificationSettings = {
  // properties only available on iOS
  // unavailable settings will not be included in the response object
  alert?: boolean;
  badge?: boolean;
  sound?: boolean;
  carPlay?: boolean;
  criticalAlert?: boolean;
  provisional?: boolean;
  providesAppSettings?: boolean;
  lockScreen?: boolean;
  notificationCenter?: boolean;
};

function checkNotifications(): Promise<{
  status: PermissionStatus;
  settings: NotificationSettings;
}>;
import {checkNotifications} from 'react-native-permissions';

checkNotifications().then(({status, settings}) => {
  // …
});

requestNotifications

Request notifications permission status and get notifications settings values.

  • You have to target at least SDK 33 to perform request on Android 13+.
  • You cannot request notifications permissions on Windows. Disabling / enabling them can only be done through the App Settings.
// only used on iOS
type NotificationOption =
  | 'alert'
  | 'badge'
  | 'sound'
  | 'criticalAlert'
  | 'carPlay'
  | 'provisional'
  | 'providesAppSettings';

type NotificationSettings = {
  // properties only available on iOS
  // unavailable settings will not be included in the response object
  alert?: boolean;
  badge?: boolean;
  sound?: boolean;
  carPlay?: boolean;
  criticalAlert?: boolean;
  provisional?: boolean;
  providesAppSettings?: boolean;
  lockScreen?: boolean;
  notificationCenter?: boolean;
};

function requestNotifications(options: NotificationOption[]): Promise<{
  status: PermissionStatus;
  settings: NotificationSettings;
}>;
import {requestNotifications} from 'react-native-permissions';

requestNotifications(['alert', 'sound']).then(({status, settings}) => {
  // …
});

checkMultiple

Check multiples permissions in parallel.

⚠️  Android will never return blocked on checkMultiple, you have to call requestMultiple to get the info.

function checkMultiple<P extends Permission[]>(
  permissions: P,
): Promise<Record<P[number], PermissionStatus>>;
import {checkMultiple, PERMISSIONS} from 'react-native-permissions';

checkMultiple([PERMISSIONS.IOS.CAMERA, PERMISSIONS.IOS.FACE_ID]).then((statuses) => {
  console.log('Camera', statuses[PERMISSIONS.IOS.CAMERA]);
  console.log('FaceID', statuses[PERMISSIONS.IOS.FACE_ID]);
});

requestMultiple

Request multiple permissions in sequence.

function requestMultiple<P extends Permission[]>(
  permissions: P,
): Promise<Record<P[number], PermissionStatus>>;
import {requestMultiple, PERMISSIONS} from 'react-native-permissions';

requestMultiple([PERMISSIONS.IOS.CAMERA, PERMISSIONS.IOS.FACE_ID]).then((statuses) => {
  console.log('Camera', statuses[PERMISSIONS.IOS.CAMERA]);
  console.log('FaceID', statuses[PERMISSIONS.IOS.FACE_ID]);
});

openSettings

Open application settings.

function openSettings(): Promise<void>;
import {openSettings} from 'react-native-permissions';

openSettings().catch(() => console.warn('cannot open settings'));

openPhotoPicker (iOS 14+)

Open a picker to update the photo selection when PhotoLibrary permission is limited. This will reject if unsupported or if full permission is already granted.

function openPhotoPicker(): Promise<void>;
import {openPhotoPicker} from 'react-native-permissions';

openPhotoPicker().catch(() => {
  console.warn('Cannot open photo library picker');
});

checkLocationAccuracy (iOS 14+)

When LocationAlways or LocationWhenInUse is granted, allow checking if the user share his precise location.

type LocationAccuracy = 'full' | 'reduced';

function checkLocationAccuracy(): Promise<LocationAccuracy>;
import {checkLocationAccuracy} from 'react-native-permissions';

checkLocationAccuracy()
  .then((accuracy) => console.log(`Location accuracy is: ${accuracy}`))
  .catch(() => console.warn('Cannot check location accuracy'));

requestLocationAccuracy (iOS 14+)

When LocationAlways or LocationWhenInUse is granted, allow requesting the user for his precise location. Will resolve immediately if full accuracy is already authorized.

type LocationAccuracyOptions = {
  purposeKey: string;
};

type LocationAccuracy = 'full' | 'reduced';

function requestLocationAccuracy(options: LocationAccuracyOptions): Promise<LocationAccuracy>;
import {requestLocationAccuracy} from 'react-native-permissions';

requestLocationAccuracy({purposeKey: 'YOUR-PURPOSE-KEY'})
  .then((accuracy) => console.log(`Location accuracy is: ${accuracy}`))
  .catch(() => console.warn('Cannot request location accuracy'));

About iOS LOCATION_ALWAYS permission

If you are requesting PERMISSIONS.IOS.LOCATION_ALWAYS, there won't be a Always Allow button in the system dialog. Only Allow Once, Allow While Using App and Don't Allow. This is expected behaviour, check the Apple Developer Docs.

When requesting PERMISSIONS.IOS.LOCATION_ALWAYS, if the user choose Allow While Using App, a provisional "always" status will be granted. The user will see While Using in the settings and later will be informed that your app is using the location in background. That looks like this:

Screenshot

Subsequently, if you are requesting LOCATION_ALWAYS permission, there is no need to request LOCATION_WHEN_IN_USE. If the user accepts, LOCATION_WHEN_IN_USE will be granted too. If the user denies, LOCATION_WHEN_IN_USE will be denied too.

Testing with Jest

If you don't already have a Jest setup file configured, please add the following to your Jest configuration file and create the new jest.setup.js file in project root:

setupFiles: ['<rootDir>/jest.setup.js'];

You can then add the following line to that setup file to mock the NativeModule.RNPermissions:

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

Sponsors

This module is provided as is, I work on it in my free time.

If you or your company uses it in a production app, consider sponsoring this project πŸ’°. You also can contact me for premium enterprise support: help with issues, prioritize bugfixes, feature requests, etc.

Sponsors list

react-native-permissions's People

Contributors

adapptor-kurt avatar bienur avatar bzoz avatar cesargdm avatar charlesmangwa avatar danieldkim avatar darinwilson avatar dependabot[bot] avatar erezrokah avatar eugenehp avatar friederbluemle avatar geraintwhite avatar hectoruiz avatar jasongaare avatar jastanton avatar jochem725 avatar jsimonassi avatar keksike avatar kida7 avatar king6cong avatar kottidev avatar moox avatar peterlau avatar princekurt avatar rohantalip avatar sandromachado avatar trestrantham avatar vspedr avatar yonahforst avatar zoontek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-permissions's Issues

requesting permission for microphone fails using the ios simulator

calling:
Permissions.requestPermission('microphone')
.then((permissionMicrophone) => {
console.log('permissionMicrophone:', permissionMicrophone);

results in:
2017-01-02 09:22:26.381 [info][tid:com.facebook.react.JavaScript] 'permissionMicrophone:', 'undetermined'

when using the simulator. It also does not show microphone in the settings where permissions are handled.

screen shot 2017-01-02 at 9 22 42

Anyone else seeing this? I wonder if this is an issue with the xcodes simulator since it works fine using an actual device.

Cannot read property 'getPermissionStatus' of undefined

Hello!

I keep getting this error when calling checkMultiplePermissions(['camera', 'photo']) on iOS. I added the library(the app is built correctly), added the descriptions to this permissions, nothing helps. Can you advise anything?

image

IOS Crash

Hi i am new to IOS development. I installed react-native-permissions but the ios simulator app wont start now.

  • when running from xcode, this shows
    screen shot 2016-12-24 at 7 35 00 pm

  • when running react-native run-ios, this shows
    An error was encountered processing the command (domain=NSMachErrorDomain, code=-308): The operation couldn’t be completed. (Mach error -308 - (ipc/mig) server died)

I followed your steps correctly:

  1. npm install --save react-native-permissions
  2. rnpm link

what am i missing here?

Array.includes is undefined

I'm getting undefined from line 71 !this.getPermissionTypes().includes(permission):

requestPermission(permission, type) {
    let options; 

    if (!this.getPermissionTypes().includes(permission)) {
        return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on ${Platform.OS}`)
    } else if (permission == 'backgroundRefresh'){
        return Promise.reject('ReactNativePermissions: You cannot request backgroundRefresh')
    } else if (permission == 'location') {
        options = type || 'whenInUse'
    } else if (permission == 'notification') {
        options = type || ['alert', 'badge', 'sound']
    }

    return RNPermissions.requestPermission(permission, options)
}

I'm thinking that perhaps the polyfill needs to be included in the library?

Request Location Permission Mode

Thank you for the awesome job, I have a question and hope someone can help, the issue is actually related to react-native itself rather than react-native-permissions; I'm working on an app which has few different types of users, for some users I should beg for "Allow access to location while using the app" while other types of users would willingly "Allow access always", I have both NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription set in Info.plist, your library does an awesome job checking and requesting a specific type of location tracking permission, but as soon as I call navigator.geolocation.getCurrentPosition() it will pop the "allow always" dialog only because its been set in Info.plist, even when the user has already permitted "while using", this is very annoying from UX point of view and I'm thinking about writing a native module for tracking the location for those users and use it instead of react-native's navigator, but before that I thought maybe someone has already found a workaround for this.

Xcode : Argument list too long problem on Example

I have this error on Xcode that cause a build error :

Argument list too long: recursive header expansion failed at /Users/arthurlorent/workspace/ecovelo-mobile/ios/../node_modules/react-native-permissions/Example/ios.

I have removed the the Example folder and the error is gone.
I am using react-native v0.37.

Android openSettings

openSettings for Android opens application settings which just shows list of permissions for that app. We cannot change permissions like in iOS. It would be better if openSettings for Android opens device settings (ACTION_SETTINGS) instead of app settings (ACTION_APPLICATION_DETAILS_SETTINGS).

request Bluetooth permission open it and print undetermined

Version

react-native : 0.41.1
lottie-react-native: 1.0.6
lottie-ios: 1.0.2
Xcode: 8.2.1

Code

checkPermission = () => {
    Permissions.requestPermission('bluetooth')
        .then(response => console.log('bluetooth', response))
};

Run app on device iOS 10.
It will popup alert, and I click Setting, to open Bluetooth. then check again.

Console

bluetooth undetermined

Is it Right?

and why not support check bluetooth on android? If not support, We will find other library to check it. @yonahforst Do you have plan to do it?

Build failure - Missing libReactNativePermissions.a

Hello,

I can't seem to get this working, using React Native and have followed these steps from the readme:

  • npm install --save react-native-permissions
  • rnpm link

Then running react-native run-ios results in:

Found Xcode project CandidateApp.xcodeproj
Launching iPhone 6 (9.3)...
Building using "xcodebuild -project CandidateApp.xcodeproj -scheme CandidateApp -destination id=EDA8ACD0-CC57-4E0D-9126-3913C8991B17 -derivedDataPath build"
User defaults from command line:
    IDEDerivedDataPathOverride = /Users/tom/Projects/candidate-native-app/ios/build

=== BUILD TARGET RNI18n OF PROJECT RNI18n WITH CONFIGURATION Debug ===

Check dependencies

=== BUILD TARGET RCTLinking OF PROJECT RCTLinking WITH CONFIGURATION Debug ===
Check dependencies

=== BUILD TARGET RCTWebSocket OF PROJECT RCTWebSocket WITH CONFIGURATION Debug ===
Check dependencies

=== BUILD TARGET ReactNativePermissions OF PROJECT ReactNativePermissions WITH CONFIGURATION Debug ===

Check dependencies
Unable to run command 'Libtool libReactNativePermissions.a' - this target might include its own product.

=== BUILD TARGET RCTVibration OF PROJECT RCTVibration WITH CONFIGURATION Debug ===

Check dependencies

=== BUILD TARGET ReactNativeConfig OF PROJECT ReactNativeConfig WITH CONFIGURATION Debug ===
Check dependencies

=== BUILD TARGET RCTActionSheet OF PROJECT RCTActionSheet WITH CONFIGURATION Debug ===

Check dependencies

=== BUILD TARGET React OF PROJECT React WITH CONFIGURATION Debug ===
Check dependencies

** BUILD FAILED **


The following build commands failed:
    Check dependencies
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/CandidateApp.app
Launching org.reactjs.native.example.CandidateApp
org.reactjs.native.example.CandidateApp: 14142

I opened my project in xCode and found that libReactNativePermissions.a is missing in the ReactNativePermissions project. Any ideas?

Cheers.

Documentation missing for new important iOS Info.plist keys to avoid app crash upon requesting permission

As of Xcode 8 and React Native 0.33 it is now necessary to add kit specific "permission" keys to your Xcode Info.plist file, in order to make requestPermission work. Otherwise your app crashes when requesting the specific permission. I discovered this after days of frustration.

Apple Developer Forum thread about the issue: https://forums.developer.apple.com/thread/48959

The solution is:
Open Xcode > Info.plist > Add a key (starting with "Privacy - ...") with your kit specific permission. The value for the key is optional.

Example:
If you need Contacts permission you have to add the key "Privacy - Contacts Usage Description".

screen shot 2016-09-21 at 13 13 21

It might be helpful to add to the documentation.

Example File error on iOS

Getting the following build error for mipmap-mdli on iOS

Argument list too long: recursive header expansion failed at ... /node_modules/react-native-permissions/Example/android/app/src/main/res/mipmap-mdpi.

If I remove the Example file everything builds correctly.

Error trying to checkMultiplePermissions

Code being used:

function CheckPermissions(flow) {
  try {
    Permissions.checkMultiplePermissions(
      ['location', 'photo', 'camera', 'contacts', 'notification']
    ).then(perms => {
        console.debug('checked permissions', arguments);
      },
      () => {
        console.debug('checked permissions failed', arguments);
      }
    );
  }
  catch (e) {
    console.debug('checked permissions failed', e);
  }
}

Error:

 TypeError: Cannot read property 'getPermissionStatus' of undefined

It seems the reference of that is undefined.

Logic Error in Location Permission

Hi,
from my perspective there is a problem with the location permission and their options (always, whenInUse). I my app the location permission with option always is required but if the user sets it manually to whenInUse via device settings the permission request responses authorized. I've debugged a bit and found the reason in RNPLocation.m. When doing a request the first thing that is done is checking the status via getStatus. There, in both cases (always and whenInUse) authorized is returned.

...
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            return RNPStatusAuthorized;
...

Now there is no logic in request method that does check the option parameter (always) that I have passed. That's why I get authorized from the api even it was not set to always in settings.

Please have an eye on it.

Thanks in advance. Norman

Add detailed explanation for SDK versions (Android)

Hi!
Great package, good work!

I was having a problem, but when I started writing this issue I figured it out.

As you can see in the screenshot, the result is different. To the left is your example app, and my app is to the right. I have copied your code exactly, but still get different result.

screen shot 2017-01-12 at 10 29 55

They are running on the same emulator, with Android SDK 25.

Answer: It is confusing to have SDK versions in both AndroidManifest.xml and android/app/build.gradle. I removed them from AndroidManifest.xml and updated values in build.gradle
AndroidManifest.xml:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.READ_CALENDAR"/>

    // I removed following lines
    /*
    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="23" />
    */

android/app/build.gradle

...
android {
    compileSdkVersion 25 // Changed to latest SDK
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.suvapp"
        minSdkVersion 16 // Decreased this to allow older devices use the app
        targetSdkVersion 25 // Target latest SDK
...

This isn't a bug, but I think that people who are new to configure Android apps will have a hard time understanding how to use permissions at runtime.

Do you @yonahforst think this is something that could be added to README?

"denied" response when locking screen

When popup is opened, locking the screen will result in a "denied" response, when resuming the application the popup is still opened.

Causing issues to determine the user input in this scenario.

Thanks

Denied from appstore

Dear developer,

We have discovered one or more issues with your recent delivery for "Ahead!". 
To process your delivery, the following issues must be corrected:

This app attempts to access privacy-sensitive data without a usage description. 
The app's Info.plist must contain an NSCalendarsUsageDescription key with a string 
value explaining to the user how the app uses this data.

This app attempts to access privacy-sensitive data without a usage description. 
The app's Info.plist must contain an NSBluetoothPeripheralUsageDescription key with a string 
value explaining to the user how the app uses this data.

Once these issues have been corrected, you can then redeliver the corrected binary.

Regards,

The App Store team

this is what i do

    _handleAppStateChange = (appState) => {
      if (appState == 'active') {
          /*
           Setup redux store with right permissions to be used accross the app
          */
          Permissions.checkMultiplePermissions(Permissions.getPermissionTypes())
              .then( status => {
                  this.props.dispatch_permissions_set_all_permissions(status);
              });
      }
    }

An at one point in my app i do this

: {text: 'Open Settings', onPress: Permissions.openSettings},

And this

Permissions.requestPermission("camera")

I don't se how this would affect the above mentioned permissions.

Add js file for Android so it doesn't crash

I'm attempting to use this module along with react-native-android-permissions, the issue is that requiring this module throws the following error.

screenshot 2016-06-02 14 09 01

I've forked and fixed it by adding a ReactNativePermissions.android.js as placeholder.

Would you accept a PR?

App crash when refuse the alert

If I refuse the 'alert' that asks me if I want to allow location the app throws me a error:

screen shot 2017-02-16 at 19 54 05

But the permission is write in AndroidManifest.xml and if I accept the alert the app gets my location correctly.

EDIT: Sorry, I solved it. I was calling the getCurrentPosition when refused.

Android build error with React Native 0.33

Hi,

With React Native 0.33, I get the following error when I try to build my app for Android:

:react-native-permissions:compileReleaseJavaWithJavac
/Users/mvila/Projects/enchante-app/node_modules/react-native-permissions/android/src/main/java/com/joshblour/reactnativepermissions/ReactNativePermissionsModule.java:82: error: method requestPermission in class PermissionsModule cannot be applied to given types;
    mPermissionsModule.requestPermission(permission, new Callback() {
                      ^
  required: String,Promise
  found: String,<anonymous Callback>,<null>
  reason: actual and formal argument lists differ in length
1 error
:react-native-permissions:compileReleaseJavaWithJavac FAILED

I guess there is a breaking change in 0.33.

Storage permission missing

First, thanks for your nice package that is working like a charm.

I just noticed that there is one important missing permission for Android.
Indeed, there is no way to ask permission for the Android READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGEpermissions that are required to use some other packages as https://github.com/bamlab/react-native-image-resizer or https://github.com/johanneslumpe/react-native-fs that are manipulating files and stuff in the device storage.

I had to use http://facebook.github.io/react-native/releases/0.37/docs/permissionsandroid.html in order to request the storage permission.
It would be great to add it to your package !

Latest commits in Master breaks <= RN 0.39

The latest commits in master breaks in versions of React Native <= 0.39. Could this package versions be identified in specific Release versions so that we can safely assign the version numbers in our package.json and avoid breaks?

Does "restricted" apply to all permission types?

I'm trying to understand restricted. Can the camera or microphone permission return restricted? Can you give me some examples of when restricted is returned when getPermissionStatus() is called?

Build failed

error: method requestPermission in class PermissionsModule cannot be applied to given types;
mPermissionsModule.requestPermission(permission, new PromiseImpl(resolve, reject));

How to Test Components?

I have a component that uses this module to check for and acquire the user's location.

    Permissions.getPermissionStatus('location')
      .then((response) => { ... });

When I run my unit test suite (Enzyme) on this component, I get the following error:

TypeError: Cannot read property 'getPermissionStatus' of undefined
      at ReactNativePermissions.getPermissionStatus (node_modules/react-native-permissions/ReactNativePermissions.js:62:11)

How does one test their components that use this module? Is there a way to mock this out?

[iOS]Β Permissions.openSettings() -> change permission -> app crashes

Hi,

first of all, thanks for this component πŸ‘

I have a little problem with Permissions.openSettings() (using version 0.2.5) - as mentioned in the title, as soon as I change the permissions of, e.g., my camera, the app crashes.. No error message, nothing..

screen shot 2017-01-17 at 18 30 23

  • desciptions for Camera and Photos usage are added in Info.plist
  • don't know if that has something to do with this or another comonent, but when running rnpm link, I get the error ERR! ERRPLIST Could not locate Info.plist. Check if your project has 'INFOPLIST_FILE' set properly

Any idea what could be the problem..?

requestPermission will not register if permission has already been requested once (even if it was authorized)

This may or may not be a general problem, but it's problematic for our app and diverges from how React Native's built-in PushNotificationsIOS works, so I wanted to raise it.

https://github.com/yonahforst/react-native-permissions/blob/master/permissions/RNPNotification.m#L49

This stops registerForRemoteNotifications / registerForRemoteNotificationTypes being called if the user has been asked for permission already. When users log out of our app we unregister their push endpoint. When they log in again this line prevents them being registered because the user defaults flag will be true.

android can not link the library

After following the android linking guide, can not link the library

React Native 0.33

error:
react-native-permissions:compileReleaseJavaWithJavac FAILED

Android: Could not expand ZIP ... 'react-native-permissions-release.aar'

The auto linker didn't automatically include the include the "compile project(':react-native-permissions')" in the app\build.gradle file. After addressing that, I get an error

"Could not expand ZIP '...react-native-permissions-release.aar', which I am guessing means there was a problem with the aar that gradle created, but I don't really have any other debug information (I'm a little new to react-native and building android apps in general).

"undetermined" (not "denied") is returned after selecting "never ask again" in Android permission dialog

Thanks for this great little library!

Just a little bug I've run into:
On Android, shouldShowRequestPermissionRationale indicates whether we should explain to the user why we need the permission, not whether the user has been presented with the permission dialog.

It returns false in two cases:

  1. We have not asked the user for this perimssion yet.
  2. We have asked the user for this permission at least two times, and the user selected "never ask again" last time we tried.

As a result, if a user selects "never ask again", getPermissionStatus and requestPermission will return "undetermined" instead of "denied".

Code:
ReactNativePermissionsModule.java#L64

Missing libReactNativePermissions.a

Hey, thanks for this library β€”Β it fits my use case perfectly.

I didn't see libReactNativePermissions.a anywhere in the repo (per the installation instructions in the README) or in the npm package. Was it omitted by accident, or is there something I'm missing on my end?

Thanks!

** BUILD FAILED **

I get this error when trying to run on IOS:

** BUILD FAILED **

The following build commands failed:
CompileC /Users/katarina/AndroidStudioProjects/reactnative-kitchensink/ios/build/
Build/Intermediates/ReactNativePermissions.build/Debug-iphonesimulator/ReactNativePermiss
ions.build/Objects-normal/x86_64/ReactNativePermissions.o ReactNativePermissions.m normal
x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)

Installing build/Build/Products/Debug-iphonesimulator/kitchensink.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/
Debug-iphonesimulator/kitchensink.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

I tried to link library manually but I can't find "libReactNativePermissions.a" file.

NativeModules.ReactNativePermissions is undefined

I tried this import Permissions from 'react-native-permissions'; and Permissions is undefined.

Also tried import {NativeModules} from 'react-native'; and NativeModules.ReactNativePermissions is undefined.

And yes I do have it linked in my xcode.
screenshot

Great utility! Is Android in the roadmap?

Hi,
Thanks for this utility! Just wondering if there was an Android app equivalent? I'm just checking as I do want to support Android at one stage. Same behaviour, no reprompt - we'll guide the user into providing the required access if required.

Thanks

undefined is not a object (evaluating 'RNPermissions.requestPermissions') RN = 0.31

Hi yonahforst, thanks for this module!

I'm unable do request location permission using RN 0.31. It seems like RN change it NativeModules structure and now this doens't work anymore

var RNPermissions = ReactNative.NativeModules.ReactNativePermissions;

So i get this error (title of this issue) in the line 81 of ReactNativePermissions.js

    requestPermission(permission, type) {
        let options;

        if (this.getPermissionTypes().indexOf(permission) === -1) {
            return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on ${Platform.OS}`)
        } else if (permission == 'backgroundRefresh'){
            return Promise.reject('ReactNativePermissions: You cannot request backgroundRefresh')
        } else if (permission == 'location') {
            options = type || 'whenInUse'
        } else if (permission == 'notification') {
            options = type || ['alert', 'badge', 'sound']
        }

        return RNPermissions.requestPermission(permission, options)
    }

I tried to fix it locally, but then an exception in BaseJavaModule.java was thrown. Something about a number of parameters.

is there other reports like this?

If you need more information, let me know

"photo" or "photos" ?

Hi @yonahforst, I'm developing for android and iOS and the permission identifier for photos is different on these platforms. I have to use "photos" on Android and "photo" on iOS. Can you roger that? Seems like a bug?!?

Using "react-native-permissions": "^0.2.4"

Thank you in advance.

UpperCase permission string problem

permission.toUpperCase() (in ReactNativePermissionsModule.java:117) converts "microphone" to "MΔ°CROPHONE" so we get "MΔ°CROPHONE is not a constant in com.jshblour.reactnativepermissions.ReactNativePermissionsModule$RNType"

when we try to use MICROPHONE instead of "microphone" ==> "Possible Unhandled Promise Rejection" and module is not working...

ReactNativePermissions: photoPermissionStatus is depricated. Use getPermissionStatus('photo') instead.

react-native: 0.27

When i tried to use getPermissionStatus('photo') i got an 'is not a function' error.

So i started to use Permissions.default.photoPermissionStatus() which looks like depricated. Also there isn't an openSettings function in this object.

This is the Permissions object when i require 'react-native-permissions'

{ default: 
   { StatusUndetermined: 'undetermined',
     StatusDenied: 'denied',
     StatusAuthorized: 'authorized',
     StatusRestricted: 'restricted',
     locationPermissionStatus: [Function],
     cameraPermissionStatus: [Function],
     microphonePermissionStatus: [Function],
     photoPermissionStatus: [Function],
     contactsPermissionStatus: [Function],
     eventPermissionStatus: [Function],
     reminderPermissionStatus: [Function],
     bluetoothPermissionStatus: [Function],
     notificationPermissionStatus: [Function],
     backgroundRefreshPermissionStatus: [Function] } }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.