Browse Source

added support for legacy methods with deprication warnings. updated readme

Yonah Forst 8 years ago
parent
commit
f8821fecd6
2 changed files with 120 additions and 51 deletions
  1. 87
    46
      README.md
  2. 33
    5
      ReactNativePermissions.ios.js

+ 87
- 46
README.md View File

@@ -1,69 +1,110 @@
1 1
 # React Native Permissions
2
-Check user permissions (iOS only)
3
-
4
-##What
5
-Some iOS features require the user to grant permission before you can access them.
6
-
7
-This library lets you check the current status of those permissions. (Note: it _doesn't_ prompt the user, just silently checks the permission status)
2
+Request user permissions from React Native (iOS only - android coming soon)
8 3
 
9 4
 The current supported permissions are:
5
+- Push Notifications
10 6
 - Location
11 7
 - Camera
12 8
 - Microhone
13 9
 - Photos
14 10
 - Contacts
15
-- Event
11
+- Events
12
+- Reminders
16 13
 - Bluetooth (Peripheral role. Don't use for Central only)
17
-- RemoteNotifications (Push Notifications)
14
+- Background Refresh
18 15
 
19
-####Example
20
-```java
16
+####General Usage
17
+```js
21 18
 const Permissions = require('react-native-permissions');
22 19
 
23
-//....
20
+//...
21
+  //check the status of a single permission
24 22
   componentDidMount() {
25
-    Permissions.locationPermissionStatus()
26
-    .then(response => {
27
-      if (response == Permissions.StatusUndetermined) {
28
-        console.log("Undetermined");
29
-      } else if (response == Permissions.StatusDenied) {
30
-        console.log("Denied");
31
-      } else if (response == Permissions.StatusAuthorized) {
32
-        console.log("Authorized");
33
-      } else if (response == Permissions.StatusRestricted) {
34
-        console.log("Restricted");
35
-      }
36
-    });
23
+    Permissions.getPermissionStatus('photo')
24
+      .then(response => {
25
+        //response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
26
+        this.setState({ photoPermission: response })
27
+      });
37 28
   }
38
-//...
39
-```
40
-
41
-
42
-####API
43
-
44
-As shown in the example, methods return a promise with the authorization status as an `int`. You can compare them to the following statuses: `StatusUndetermined`, `StatusDenied`, `StatusAuthorized`, `StatusRestricted`
45
-
46
-`locationPermissionStatus()` - checks for access to the user's current location. Note: `AuthorizedAlways` and `AuthorizedWhenInUse` both return `StatusAuthorized`
47
-
48
-`cameraPermissionStatus()` - checks for access to the phone's camera
49 29
 
50
-`microphonePermissionStatus()` - checks for access to the phone's microphone
51
-
52
-`photoPermissionStatus()` - checks for access to the user's photo album
53
-
54
-`contactsPermissionStatus()` - checks for access to the user's address book
55
-
56
-`eventPermissionStatus(eventType)` - requires param `eventType`; either `reminder` or `event`. Checks for access to the user's calendar events and reminders
30
+  //request permission to access photos
31
+  _requestPermission() {
32
+    Permissions.requestPermission('photo')
33
+      .then(response => {
34
+        //returns once the user has chosen to 'allow' or to 'not allow' access
35
+        //response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
36
+        this.setState({ photoPermission: response })
37
+      });
38
+  }
57 39
 
58
-`bluetoothPermissionStatus()` - checks the authorization status of the `CBPeripheralManager` (for sharing data while backgrounded). Note: _Don't_ use this if you're only using `CBCentralManager`
40
+  //check the status of multiple permissions
41
+  _checkCameraAndPhotos() {
42
+    Permissions.checkMultiplePermissions(['camera', 'photo'])
43
+      .then(response => {
44
+        //response is an object mapping type to permission
45
+        this.setState({ 
46
+          cameraPermission: response.camera,
47
+          photoPermission: response.photo,
48
+        })
49
+      });
50
+  }
59 51
 
60
-`notificationPermissionStatus()` - checks if the user has authorized remote push notifications. Note: iOS only tells us if the user has ever registered for notification, and which notifications are enabled. Therefore we cannot tell the difference between a user who has never been prompted for notification and a user who denied permission; both will return `StatusUndetermined`. You can determine if `StatusUndetermined` is actually `StatusDenied` by keeping track of whether or not you've already asked the user for permission. This promise *can* return `StatusDenied` if the user switched notifications off from the settings menu. Confusing, I know...
52
+  // this is a common pattern when asking for permissions.
53
+  // iOS only gives you once chance to show the permission dialog, 
54
+  // after which the user needs to manually enable them from settings.
55
+  // the idea here is to explain why we need access and determine if
56
+  // the user will say no, so that we don't blow our one chance.
57
+  // if the user already denied access, we can ask them to enable it from settings.
58
+  _alertForPhotosPermission() {
59
+    Alert.alert(
60
+      'Can we access your photos?',
61
+      'We need access so you can set your profile pic',
62
+      [
63
+        {text: 'No way', onPress: () => console.log('permission denied'), style: 'cancel'},
64
+        this.state.photoPermission == 'undetermined'? 
65
+          {text: 'OK', onPress: this._requestPermission.bind(this)}
66
+          : {text: 'Open Settings', onPress: Permissions.openSettings}
67
+      ]
68
+    )
69
+  }
70
+//...
71
+```
61 72
 
62
-`backgroundRefreshStatus()` - checks the authorization status of background refresh
73
+####API
63 74
 
75
+_Permission statuses_ - `authorized`, `denied`, `restricted`, or `undetermined`
76
+
77
+_Permission types_ - `location`, `camera`, `microphone`, `photo`, `contacts`, `event`, `reminder`, `bluetooth`, `notification`, or `backgroundRefresh`
78
+
79
+| Method Name | Arguments | Notes
80
+|---|---|---|
81
+| `getPermissionStatus` | `type` | - Returns a promise with the permission status. Note: for type `location`, iOS `AuthorizedAlways` and `AuthorizedWhenInUse` both return `authorized` |
82
+| `requestPermission` | `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. Note: see below for special cases|
83
+| `checkMultiplePermissions` | `[types]` | - Accepts an array of permission types and returns a promise with an object mapping permission types to statuses |
84
+| `getPermissionTypes` | *none* | - Returns an array of valid permission types  |
85
+| `openSettings` | *none* | - Switches the user to the settings page of your app (iOS 8.0 and later)  |
86
+| `canOpenSettings` | *none* | - Returns a boolean indicating if the device supports switching to the settings page |
87
+
88
+Note: Permission type `bluetooth` represents the status of the `CBPeripheralManager` . Note: Don't use this if you're only using `CBCentralManager`
89
+
90
+#####Special cases
91
+
92
+`requestPermission` also accepts a second parameter for types `location` and `notification`.
93
+- `location`: the second parameter is a string, either `always` or `whenInUse`(default).
94
+- `notification`: the second parameter is an array with the desired alert types. Any combination of `alert`, `badge` and `sound` (default requests all three)
95
+*_example_*
96
+```js
97
+    Permissions.requestPermission('location', 'always')
98
+      .then(response => {
99
+        this.setState({ locationPermission: response })
100
+      })
101
+
102
+    Permissions.requestPermission('notification', ['alert', 'badge'])
103
+      .then(response => {
104
+        this.setState({ notificationPermission: response })
105
+      })
106
+```
64 107
 
65
-You also can open the Settings app.
66
-`openSettings()` - open the Settings app. Note: this is only supported in ios >= 8. You can use `canOpenSettings()` to determine if it's supported.
67 108
 
68 109
 ##Setup
69 110
 

+ 33
- 5
ReactNativePermissions.ios.js View File

@@ -3,8 +3,36 @@
3 3
 var React = require('react-native');
4 4
 var RNPermissions = React.NativeModules.ReactNativePermissions;
5 5
 
6
+const RNPTypes = [
7
+	'location',
8
+	'camera',
9
+	'microphone',
10
+	'photo',
11
+	'contacts',
12
+	'event',
13
+	'reminder',
14
+	'bluetooth',
15
+	'notification',
16
+	'backgroundRefresh', 
17
+]
6 18
 
7 19
 class ReactNativePermissions {
20
+	constructor() {
21
+		//legacy support
22
+		this.StatusUndetermined = 'undetermined'
23
+		this.StatusDenied = 'denied'
24
+		this.StatusAuthorized = 'authorized'
25
+		this.StatusRestricted = 'restricted'
26
+
27
+		RNPTypes.forEach(type => {
28
+			let methodName = `${type}PermissionStatus`
29
+			this[methodName] = p => {
30
+				console.warn(`ReactNativePermissions: ${methodName} is depricated. Use getPermissionStatus('${type}') instead.`)
31
+				return this.getPermissionStatus(p == 'reminder' ? p : type)
32
+			}
33
+		})
34
+	}
35
+
8 36
 	canOpenSettings() {
9 37
 		return RNPermissions.canOpenSettings()
10 38
 	}
@@ -14,11 +42,11 @@ class ReactNativePermissions {
14 42
 	}
15 43
 
16 44
 	getPermissionTypes() {
17
-		return RNPermissions.PermissionTypes;
45
+		return RNPTypes;
18 46
 	}
19 47
 
20 48
 	getPermissionStatus(permission) {
21
-		if (RNPermissions.PermissionTypes.includes(permission)) {
49
+		if (RNPTypes.includes(permission)) {
22 50
 			return RNPermissions.getPermissionStatus(permission)
23 51
 		} else {
24 52
 			return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type`)
@@ -28,7 +56,7 @@ class ReactNativePermissions {
28 56
 	requestPermission(permission, type) {
29 57
 		switch (permission) {
30 58
 			case "location":
31
-				return RNPermissions.requestLocation(type)
59
+				return RNPermissions.requestLocation(type || 'always')
32 60
 			case "camera":
33 61
 				return RNPermissions.requestCamera();
34 62
 			case "microphone":
@@ -44,7 +72,7 @@ class ReactNativePermissions {
44 72
 			case "bluetooth":
45 73
 				return RNPermissions.requestBluetooth();
46 74
 			case "notification":
47
-				return RNPermissions.requestNotification(type)
75
+				return RNPermissions.requestNotification(type || ['alert', 'badge', 'sound'])
48 76
 			case "backgroundRefresh":
49 77
 				return Promise.reject('You cannot request backgroundRefresh')
50 78
 			default:
@@ -78,4 +106,4 @@ class ReactNativePermissions {
78 106
 	}
79 107
 }
80 108
 
81
-export default new ReactNativePermissions();
109
+export default new ReactNativePermissions()