npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-native-custom-permissions

v1.0.4

Published

Check user permissions in React Native

Downloads

4

Readme

☝🏼 React Native Contacts Permissions

original repo https://github.com/yonahforst/react-native-permissions

npm version npm Platform - Android and iOS MIT styled with prettier

Request user contacts camera photo permissions from React Native, iOS + Android Because of Apple Reriew, delete unused premissions

| Version | React Native Support | | ------- | -------------------- | | 1.1.1 | 0.40 - 0.52 | | 0.2.5 | 0.33 - 0.39 |

Complies with react-native-version-support-table

⚠️ Breaking changes in version 1.0.0

  • Now using React Native's own JS PermissionsAndroid module on Android, which is great because we no longer have to do any additional linking on Android
  • Updated API to be closer to React Native's PermissionsAndroid
  • Removed openSettings() support on Android (to stay linking-free). There are several NPM modules available for this
  • restricted status now supported on Android, although it means something different than iOS

Setup

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

📌 Don't forget to add permissions to AndroidManifest.xml for android and Info.plist for iOS (Xcode >= 8). See iOS Notes or Android Notes for more details.

Additional iOS setup

Using react-native link

react-native link react-native-permissions

Using manual linking

  1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...>
  2. Go to node_modulesreact-native-permissions ➜ select ReactNativePermissions.xcodeproj
  3. Add libReactNativePermissions.a to Build Phases -> Link Binary With Libraries

Using

import Permissions from 'react-native-permissions'
// OR const Permissions = require('react-native-permissions').default
// if you use CommonJS module system

//...

export default class extends React.Component {
  //...

  // Check the status of a single permission(contacts permission)
  componentDidMount() {
    Permissions.check('contacts').then(response => {
      // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
      this.setState({ photoPermission: response })
    })
  }

  // Request permission to access contacts
  _requestPermission = () => {
    Permissions.request('contacts').then(response => {
      // Returns once the user has chosen to 'allow' or to 'not allow' access
      // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
      this.setState({ contactsPermission: response })
    })
  }

  // Check the status of multiple permissions
  _checkCameraAndPhotos = () => {
    Permissions.checkMultiple(['camera', 'contacts']).then(response => {
      //response is an object mapping type to permission
      this.setState({
        cameraPermission: response.camera,
        contactsPermission: response.contacts,
      })
    })
  }

  // This is a common pattern when asking for permissions.
  // iOS only gives you once chance to show the permission dialog,
  // after which the user needs to manually enable them from settings.
  // The idea here is to explain why we need access and determine if
  // the user will say no, so that we don't blow our one chance.
  // If the user already denied access, we can ask them to enable it from settings.
  _alertForPhotosPermission() {
    Alert.alert(
      'Can we access your photos?',
      'We need access so you can set your profile pic',
      [
        {
          text: 'No way',
          onPress: () => console.log('Permission denied'),
          style: 'cancel',
        },
        this.state.photoPermission == 'undetermined'
          ? { text: 'OK', onPress: this._requestPermission }
          : { text: 'Open Settings', onPress: Permissions.openSettings },
      ],
    )
  }

  //...
}

API

Permissions statuses

Promises resolve into one of these statuses:

| Return value | Notes | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | authorized | User has authorized this permission | | denied | User has denied this permission at least once. On iOS this means that the user will not be prompted again. Android users can be prompted multiple times until they select 'Never ask me again' | | restricted | iOS - this means user is not able to grant this permission, either because it's not supported by the device or because it has been blocked by parental controls. Android - this means that the user has selected 'Never ask me again' while denying permission | | undetermined | User has not yet been prompted with a permission dialog |

Supported permissions types

The current supported permissions are:

| | Type | iOS | Android | | ------------------ | ------------------- | --- | ------- | | Location | location | ✔️ | ✔ | | Camera | camera | ✔️ | ✔ | | Microphone | microphone | ✔️ | ✔ | | Photos | photo | ✔️ | ✔ | | Contacts | contacts | ✔️ | ✔ | | Events | event | ✔️ | ✔ | | Bluetooth | bluetooth | ✔️ | ❌ | | Reminders | reminder | ✔️ | ❌ | | Push Notifications | notification | ✔️ | ❌ | | Background Refresh | backgroundRefresh | ✔️ | ❌ | | Speech Recognition | speechRecognition | ✔️ | ❌ | | mediaLibrary | mediaLibrary | ✔️ | ❌ | | Motion Activity | motion | ✔️ | ❌ | | Storage | storage | ❌️ | ✔ | | Phone Call | callPhone | ❌️ | ✔ | | Read SMS | readSms | ❌️ | ✔ | | Receive SMS | receiveSms | ❌️ | ✔ |

Methods

| Method Name | Arguments | Notes | | ------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | check() | type | - Returns a promise with the permission status. See iOS Notes for special cases | | request() | type | - Accepts any permission type except backgroundRefresh. If the current status is undetermined, shows the permission dialog and returns a promise with the resulting status. Otherwise, immediately return a promise with the current status. See iOS Notes for special cases | | checkMultiple() | [types] | - Accepts an array of permission types and returns a promise with an object mapping permission types to statuses | | getTypes() | none | - Returns an array of valid permission types | | openSettings() | none | - (iOS only - 8.0 and later) Switches the user to the settings page of your app | | canOpenSettings() | none | - (iOS only) Returns a boolean indicating if the device supports switching to the settings page |

iOS Notes

  • Permission type bluetooth represents the status of the CBPeripheralManager. Don't use this if only need CBCentralManager
  • Permission type location accepts a second parameter for request() and check(); the second parameter is a string, either always or whenInUse (default).
  • Permission type notification accepts a second parameter for request(). The second parameter is an array with the desired alert types. Any combination of alert, badge and sound (default requests all three).
  • If you are not requesting mediaLibrary then you can remove MediaPlayer.framework from the xcode project
// example
Permissions.check('location', { type: 'always' }).then(response => {
  this.setState({ locationPermission: response })
})

Permissions.request('location', { type: 'always' }).then(response => {
  this.setState({ locationPermission: response })
})

Permissions.request('notification', { type: ['alert', 'badge'] }).then(
  response => {
    this.setState({ notificationPermission: response })
  },
)
  • You cannot request microphone permissions on the simulator.
  • With Xcode 8, you now need to add usage descriptions for each permission you will request. Open Xcode ➜ Info.plist ➜ Add a key (starting with "Privacy - ...") with your kit specific permission.

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

App Store submission disclaimer

If you need to submit you application to the AppStore, you need to add to your Info.plist all *UsageDescription keys with a string value explaining to the user how the app uses this data. Even if you don't use them.

So before submitting your app to the App Store, make sure that in your Info.plist you have the following keys:

<key>NSBluetoothPeripheralUsageDescription</key>
<string>Some description</string>
<key>NSCalendarsUsageDescription</key>
<string>Some description</string>
<key>NSCameraUsageDescription</key>
<string>Some description</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Some description</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Some description</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Some description</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Some description</string>
<key>NSAppleMusicUsageDescription</key>
<string>Some description</string>
<key>NSMotionUsageDescription</key>
<string>Some description</string>

This is required because during the phase of processing in the App Store submission, the system detects that you app contains code to request the permission X but don't have the UsageDescription key and then it rejects the build.

Please note that it will only be shown to the users the usage descriptions of the permissions you really require in your app.

You can find more information about this issue in #46.

Android Notes

  • Uses React Native's own PermissionsAndroid JS API.

  • All required permissions also need to be included in the AndroidManifest.xml file before they can be requested. Otherwise request() will immediately return denied.

  • You can request write access to any of these types by also including the appropriate write permission in the AndroidManifest.xml file. Read more here.

  • The optional rationale argument will show a dialog prompt.

// example
Permissions.request('camera', {
  rationale: {
    title: 'Cool Photo App Camera Permission',
    message:
      'Cool Photo App needs access to your camera ' +
      'so you can take awesome pictures.',
  },
}).then(response => {
  this.setState({ cameraPermission: response })
})
  • Permissions are automatically accepted for targetSdkVersion < 23 but you can still use check() to check if the user has disabled them from Settings.

You might need to elevate the targetSdkVersion version in your build.gradle:

android {
  compileSdkVersion 23 // ← set at least 23
  buildToolsVersion "23.0.1"  // ← set at least 23.0.0

  defaultConfig {
    minSdkVersion 16
    targetSdkVersion 23 // ← set at least 23
    // ...

Troubleshooting

Q: iOS - App crashes as soon as I request permission

A: Starting with Xcode 8, you need to add permission descriptions. See iOS notes for more details. Thanks to @jesperlndk for discovering this.

Q: iOS - App crashes when I change permission from settings

A: This is normal. iOS restarts your app when your privacy settings change. Just google "iOS crash permission change"