LoginSignup
5
8

More than 5 years have passed since last update.

React Nativeでカメラや現在地などのパーミッションを管理する

Last updated at Posted at 2018-05-24

使用パッケージ

2018年5月現在の方法です。

Androidは、React Native公式のPermissionsAndroidを使用します。
iOSは、react-native-permissionsというパッケージを使用します。

PermissionsAndroid

http://facebook.github.io/react-native/docs/permissionsandroid.html
インストール等不要で使えます。

サンプル

import { PermissionsAndroid } from 'react-native';

async function requestCameraPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        'title': 'Cool Photo App Camera Permission',
        'message': 'Cool Photo App needs access to your camera ' +
                   'so you can take awesome pictures.'
      }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the camera")
    } else {
      console.log("Camera permission denied")
    }
  } catch (err) {
    console.warn(err)
  }
}

react-native-permissions

Github:
https://github.com/yonahforst/react-native-permissions

iOSのパーミッション管理を行うことができるパッケージです。

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

react-native link react-native-permissions //ネイティブコードの自動書き換え

準備

iOSの場合、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>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>

サンプル

import Permissions from 'react-native-permissions'


export default class extends React.Component {
  ...
  componentDidMount() {
    Permissions.check('photo').then(response => {
      //responseには'authorized', 'denied', 'restricted', 'undetermined'のいずれかが返る

      if (response == 'undetermined') {
        Permissions.checkMultiple(['camera', 'photo']).then(response => {
          //response is an object mapping type to permission
          this.setState({
            cameraPermission: response.camera,
            photoPermission: response.photo,
          })
        }) 
      }
    })
  }
  ...
}

いまのところこんな感じのようです。

5
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8