23mofang-react-native-permissions 中文文档教程

发布于 7年前 浏览 16 项目主页 更新于 3年前

React Native Permissions

向 React Native、iOS + Android 请求用户权限

目前支持的权限有:

  • Location
  • Camera
  • Microphone
  • Photos
  • Contacts
  • Events
  • Reminders (iOS only)
  • Bluetooth (iOS only)
  • Push Notifications (iOS only)
  • Background Refresh (iOS only)
  • Speech Recognition (iOS only)
VersionReact Native Support
1.0.00.40.0 - 0.45.0
0.2.70.40.0 - 0.41.0
0.2.50.33.0 - 0.39.0
Complies with react-native-version-support-table

Breaking changes in version 1.0.0

  • Now using React Native's own JS PermissionsAndroid library on Android, which is great because now we no longer have to do any additional linking (on Android)
  • Updated API to be closer to RN'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

General Usage

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

为 android 添加权限到 manifest,为 ios 添加权限到 info.plist (xcode >=8)。 有关更多详细信息,请参见下面的注释。

const Permissions = require('react-native-permissions');

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

  //request permission to access photos
  _requestPermission() {
    Permissions.request('photo')
      .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({ photoPermission: response })
      });
  }

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

  // 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.bind(this)}
          : {text: 'Open Settings', onPress: Permissions.openSettings}
      ]
    )
  }
//...

API

Permission statuses

承诺解析为这些状态之一

Return valueNotes
authorizeduser has authorized this permission
denieduser has denied this permission at least once. On iOS this means that the user will not be prompted again. Android users can be promted multiple times until they select 'Never ask me again'
restrictediOS - 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
undetermineduser has not yet been prompted with a permission dialog

Supported permission types

NameiOSAndroid
location✔️
camera✔️
microphone✔️
photo✔️
contacts✔️
event✔️
bluetooth✔️
reminder✔️
notification✔️
backgroundRefresh✔️
speechRecognition✔️
storage❌️

Methods

Method NameArgumentsNotes
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

  • 权限类型 bluetooth 表示 CBPeripheralManager 的状态。 如果只需要 CBCentralManager 权限类型,请不要使用它

  • location 接受 request()check(); 第二个参数是一个字符串,alwayswhenInUse(默认)。

  • 权限类型 notification 接受 request() 的第二个参数。 第二个参数是一个包含所需警报类型的数组。 alertbadgesound 的任意组合(默认要求所有这三个)

///example
    Permissions.check('location', 'always')
      .then(response => {
        this.setState({ locationPermission: response })
      })

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

    Permissions.request('notification', ['alert', 'badge'])
      .then(response => {
        this.setState({ notificationPermission: response })
      })

您不能在模拟器上请求麦克风权限。

使用 Xcode 8,您现在需要为您请求的每个权限添加使用说明。 打开 Xcode > 信息.plist> 使用您的工具包特定权限添加一个密钥(以“Privacy - …”开头)。

例子: 如果您需要联系人权限,您必须添加密钥“隐私 - 联系人使用说明”。 3cde3b44-7ffd-11e6-918b-63888e33f983

Android Notes

Requires RN >= 0.29.0

使用RN自带的PermissionsAndroid JS api (http://facebook.github.io/react-native/releases/0.45/docs/permissionsandroid.html)

都需要在请求权限之前,还需要将权限包含在清单中。 否则 request() 将立即返回 denied

targetSdkVersion < 自动接受权限 23 但您仍然可以使用 check() 检查用户是否已从“设置”中禁用它们。

您还可以通过在清单中包含适当的写入权限来请求对任何这些类型的写入权限。 在此处阅读更多信息:https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous

Setup

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

Or manualy linking

iOS

  • Run open node_modules/react-native-permissions
  • Drag ReactNativePermissions.xcodeproj into the Libraries group of your app's Xcode project
  • Add libReactNativePermissions.a to `Build Phases -> Link Binary With Libraries.

Android

无需额外链接

AppStore submission disclaimer

如果您需要将应用程序提交到 AppStore,则需要添加到您的 Info.plist 所有带有字符串值的 *UsageDescription 键向用户解释应用程序如何使用此数据。 即使您不使用它们

因此,在将您的应用程序提交到 AppStore 之前,请确保在您的 Info.plist 中具有以下键:

<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>NSPhotoLibraryUsageDescription</key>
<string>Some description</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Some description</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Some description</string>

这是必需的,因为在 processing< /code> 在 AppStore 提交中,系统检测到您的应用包含请求权限 X 但没有 UsageDescription 密钥的代码并拒绝构建。

请注意,它只会向用户显示您在应用程序中真正需要的权限的使用说明。

您可以在#46 中找到有关此问题的更多信息。

Troubleshooting

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

A:从xcode 8开始,需要添加权限说明。 有关详细信息,请参阅 iOS 注释。 感谢@jesperlndk 发现了这一点。

Q: iOS - app crashes when I change permissions from settings

答:这是正常的。 当您的隐私设置更改时,iOS 会重新启动您的应用程序。 只需谷歌“ios崩溃权限更改”

React Native Permissions

Request user permissions from React Native, iOS + Android

The current supported permissions are:

  • Location
  • Camera
  • Microphone
  • Photos
  • Contacts
  • Events
  • Reminders (iOS only)
  • Bluetooth (iOS only)
  • Push Notifications (iOS only)
  • Background Refresh (iOS only)
  • Speech Recognition (iOS only)
VersionReact Native Support
1.0.00.40.0 - 0.45.0
0.2.70.40.0 - 0.41.0
0.2.50.33.0 - 0.39.0
Complies with react-native-version-support-table

Breaking changes in version 1.0.0

  • Now using React Native's own JS PermissionsAndroid library on Android, which is great because now we no longer have to do any additional linking (on Android)
  • Updated API to be closer to RN'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

General Usage

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

Add permissions to manifest for android and info.plist for ios (xcode >=8). See notes below for more details.

const Permissions = require('react-native-permissions');

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

  //request permission to access photos
  _requestPermission() {
    Permissions.request('photo')
      .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({ photoPermission: response })
      });
  }

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

  // 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.bind(this)}
          : {text: 'Open Settings', onPress: Permissions.openSettings}
      ]
    )
  }
//...

API

Permission statuses

Promises resolve into one of these statuses

Return valueNotes
authorizeduser has authorized this permission
denieduser has denied this permission at least once. On iOS this means that the user will not be prompted again. Android users can be promted multiple times until they select 'Never ask me again'
restrictediOS - 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
undetermineduser has not yet been prompted with a permission dialog

Supported permission types

NameiOSAndroid
location✔️
camera✔️
microphone✔️
photo✔️
contacts✔️
event✔️
bluetooth✔️
reminder✔️
notification✔️
backgroundRefresh✔️
speechRecognition✔️
storage❌️

Methods

Method NameArgumentsNotes
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)

///example
    Permissions.check('location', 'always')
      .then(response => {
        this.setState({ locationPermission: response })
      })

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

    Permissions.request('notification', ['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". 3cde3b44-7ffd-11e6-918b-63888e33f983

Android Notes

Requires RN >= 0.29.0

Uses RN's own PermissionsAndroid JS api (http://facebook.github.io/react-native/releases/0.45/docs/permissionsandroid.html)

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

Permissions are automatically accepted for targetSdkVersion < 23 but you can still use check() to check if the user has disabled them from Settings.

You can request write access to any of these types by also including the appropriate write permission in the Manifest. Read more here: https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous

Setup

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

Or manualy linking

iOS

  • Run open node_modules/react-native-permissions
  • Drag ReactNativePermissions.xcodeproj into the Libraries group of your app's Xcode project
  • Add libReactNativePermissions.a to `Build Phases -> Link Binary With Libraries.

Android

No additional linking required

AppStore 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 AppStore, 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>NSPhotoLibraryUsageDescription</key>
<string>Some description</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Some description</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Some description</string>

This is required because during the phase of processing in the AppStore submission, the system detects that you app contains code to request the permission X but don't have the UsageDescription key and 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 informations about this issue in #46.

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 permissions from settings

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

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文