mirror of
https://github.com/NativeScript/NativeScript.git
synced 2025-11-05 13:26:48 +08:00
feat: permissions touchups
This commit is contained in:
@@ -9,7 +9,8 @@
|
||||
"dependencies": {
|
||||
"@nativescript/core": "file:../../packages/core",
|
||||
"nativescript-theme-core": "file:../../node_modules/nativescript-theme-core",
|
||||
"@nativescript/imagepicker": "^1.0.6"
|
||||
"@nativescript/imagepicker": "^1.0.6",
|
||||
"@nativescript/permissions": "file:../../packages/permissions"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nativescript/android": "~8.2.1",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Observable, EventData, Page, Permissions, Trace } from '@nativescript/core';
|
||||
import { Observable, EventData, Page, Trace } from '@nativescript/core';
|
||||
import { Permissions } from '@nativescript/permissions';
|
||||
|
||||
let page: Page;
|
||||
|
||||
@@ -10,31 +11,50 @@ export function navigatingTo(args: EventData) {
|
||||
}
|
||||
|
||||
export class PermissionsModel extends Observable {
|
||||
permissions = ['location', 'camera', 'microphone', 'photo', 'contacts', 'event', 'reminder', 'bluetooth', 'bluetoothScan', 'notification', 'backgroundRefresh', 'speechRecognition', 'mediaLibrary', 'motion', 'location', 'callPhone', 'readSms', 'receiveSms'].map((v) => {
|
||||
return {
|
||||
name: v,
|
||||
checkPermission: this.checkPermission.bind(this),
|
||||
requestPermission: this.requestPermission.bind(this),
|
||||
};
|
||||
permissions = ['location', 'camera', 'microphone', 'photo', 'contacts', 'event', 'reminder', 'bluetooth', 'bluetoothScan', 'notification', 'backgroundRefresh', 'speechRecognition', 'mediaLibrary', 'motion', 'location', 'callPhone', 'readSms', 'receiveSms', 'requestMultiple'].map((v) => {
|
||||
if (v === 'requestMultiple') {
|
||||
return {
|
||||
name: 'Request Multiple Permissions',
|
||||
checkPermission: (args) => {
|
||||
this.checkPermission(args, ['camera', 'contacts']);
|
||||
},
|
||||
requestPermission: (args) => {
|
||||
this.requestPermission(args, ['camera', 'contacts']);
|
||||
},
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
name: v,
|
||||
checkPermission: this.checkPermission.bind(this),
|
||||
requestPermission: this.requestPermission.bind(this),
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
async checkPermission(args) {
|
||||
async checkPermission(args, multiple?: Array<string>) {
|
||||
const perm = args.object.bindingContext.name;
|
||||
try {
|
||||
console.log('checkPermission', perm);
|
||||
const result = await Permissions.check(perm, { type: 'none' });
|
||||
alert(JSON.stringify(result));
|
||||
if (multiple) {
|
||||
for (const p of multiple) {
|
||||
const result = await Permissions.check(p, { type: 'none' });
|
||||
alert(JSON.stringify(result));
|
||||
}
|
||||
} else {
|
||||
const result = await Permissions.check(perm, { type: 'none' });
|
||||
alert(JSON.stringify(result));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert(err);
|
||||
}
|
||||
}
|
||||
async requestPermission(args) {
|
||||
const perm = args.object.bindingContext.name;
|
||||
async requestPermission(args, multiple?: Array<string>) {
|
||||
const perm = multiple || args.object.bindingContext.name;
|
||||
try {
|
||||
console.log('requestPermission', perm);
|
||||
const result = await Permissions.request(perm, { type: 'none' });
|
||||
|
||||
1
packages/core/index.d.ts
vendored
1
packages/core/index.d.ts
vendored
@@ -98,7 +98,6 @@ export type { ImageAssetOptions } from './image-asset';
|
||||
export { ImageSource } from './image-source';
|
||||
export { ModuleNameResolver, _setResolver } from './module-name-resolver';
|
||||
export type { ModuleListProvider, PlatformContext } from './module-name-resolver';
|
||||
export { Permissions, PermissionStatus } from './permissions';
|
||||
export { isAndroid, isIOS, Screen, Device, platformNames } from './platform';
|
||||
export type { IDevice } from './platform';
|
||||
export { profile, enable as profilingEnable, disable as profilingDisable, time as profilingTime, uptime as profilingUptime, start as profilingStart, stop as profilingStop, isRunning as profilingIsRunning, dumpProfiles as profilingDumpProfiles, resetProfiles as profilingResetProfiles, startCPUProfile as profilingStartCPU, stopCPUProfile as profilingStopCPU } from './profiling';
|
||||
|
||||
@@ -124,8 +124,6 @@ export { ImageSource } from './image-source';
|
||||
export { ModuleNameResolver, _setResolver } from './module-name-resolver';
|
||||
export type { ModuleListProvider, PlatformContext } from './module-name-resolver';
|
||||
|
||||
// Permissions
|
||||
export { Permissions, PermissionStatus } from './permissions';
|
||||
export { isAndroid, isIOS, Screen, Device, platformNames } from './platform';
|
||||
export type { IDevice } from './platform';
|
||||
|
||||
|
||||
@@ -1,3 +1,180 @@
|
||||
# permissions
|
||||
## @nativescript/permissions
|
||||
|
||||
This library was generated with [Nx](https://nx.dev).
|
||||
Android and iOS permission handling with NativeScript.
|
||||
|
||||
* `npm install @nativescript/permissions`
|
||||
|
||||
Inspired by [react-native-permissions](https://github.com/yonahforst/react-native-permissions)
|
||||
|
||||
## API
|
||||
|
||||
### Permissions statuses
|
||||
|
||||
Promises resolve into ```[status:Status, always:boolean]``` where status is 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' |
|
||||
| `limited` | **iOS** - this means the permission is granted but with limitations |
|
||||
| `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` | ✔ | ✔(api >= 31) |
|
||||
| Reminders | `reminder` | ✔ | ❌ |
|
||||
| Push Notifications | `notification` | ✔ | ❌ |
|
||||
| Background Refresh | `backgroundRefresh` | ✔ | ❌ |
|
||||
| Speech Recognition | `speechRecognition` | ✔ | ❌ |
|
||||
| Media Library | `mediaLibrary` | ✔ | ❌ |
|
||||
| Motion Activity | `motion` | ✔ | ❌ |
|
||||
| Storage | `storage` | ❌️ | ✔ |
|
||||
| Phone Call | `callPhone` | ❌️ | ✔ |
|
||||
| Read SMS | `readSms` | ❌️ | ✔ |
|
||||
| Receive SMS | `receiveSms` | ❌️ | ✔ |
|
||||
| Media Location | `mediaLocation` | ❌️ | ✔(api >= 29) |
|
||||
| Bluetooth Scan | `bluetoothScan` | ❌️ | ✔(api >= 31) |
|
||||
| Bluetooth Connect | `bluetoothConnect` | ❌️ | ✔(api >= 31) |
|
||||
|
||||
### 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).
|
||||
* iOS 12+: The second parameter also takes this type inside of the array `providesAppNotificationSettings`.
|
||||
* If you are not requesting mediaLibrary then you can remove MediaPlayer.framework from the xcode project
|
||||
|
||||
```js
|
||||
import { Permissions } from '@nativescript/permissions';
|
||||
|
||||
// example
|
||||
Permissions.check('location', { type: 'always' }).then(response => {
|
||||
this.setState({ locationPermission: response[0] })
|
||||
})
|
||||
|
||||
Permissions.request('location', { type: 'always' }).then(response => {
|
||||
this.setState({ locationPermission: response[0] })
|
||||
})
|
||||
|
||||
Permissions.request('notification', { type: ['alert', 'badge'] }).then(
|
||||
response => {
|
||||
this.setState({ notificationPermission: response[0] })
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
* 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`.
|
||||
|
||||
<img width="338" alt="3cde3b44-7ffd-11e6-918b-63888e33f983" src="https://cloud.githubusercontent.com/assets/1440796/18713019/271be540-8011-11e6-87fb-c3828c172dfc.png">
|
||||
|
||||
#### 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:
|
||||
|
||||
```xml
|
||||
<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
|
||||
|
||||
* `check` and `request` also allows you to directly pass android permission(s) as a value or an array. This would allow to request any new permission without a required update of this plugin
|
||||
* 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](https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous).
|
||||
|
||||
* 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`:
|
||||
|
||||
```groovy
|
||||
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](https://github.com/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"
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { Trace } from '../trace';
|
||||
import { AndroidActivityRequestPermissionsEventData, AndroidApplication, android as androidApp } from '../application';
|
||||
import { getBoolean, setBoolean } from '../application-settings';
|
||||
import { AndroidActivityRequestPermissionsEventData, AndroidApplication, Application, Trace, ApplicationSettings } from '@nativescript/core';
|
||||
import { PermissionStatus } from './common';
|
||||
import { PermissionCheckOptions, PermissionsType, PermissionRationale, PermissionRequestOptions } from '.';
|
||||
|
||||
@@ -18,6 +16,10 @@ const MARSHMALLOW = 23;
|
||||
const ANDROIDQ = 29;
|
||||
const ANDROIDS = 31;
|
||||
|
||||
function getAndroidActivity() {
|
||||
return Application.android.foregroundActivity || Application.android.startActivity;
|
||||
}
|
||||
|
||||
const NativePermissionsTypes: PermissionsType[] = ['location', 'camera', 'mediaLocation', 'microphone', 'contacts', 'event', 'storage', 'photo', 'callPhone', 'readSms', 'receiveSms', 'bluetoothScan', 'bluetoothConnect', 'bluetooth'];
|
||||
type NativePermissionsNames = typeof NativePermissionsTypes; // type Names = readonly ['Mike', 'Jeff', 'Ben']
|
||||
type NativePermissions = NativePermissionsNames[number];
|
||||
@@ -90,9 +92,9 @@ function getNativePermissions(permission: NativePermissions, options?) {
|
||||
|
||||
const STORAGE_KEY = '@NSPermissions:didAskPermission:';
|
||||
|
||||
const setDidAskOnce = (permission: string) => Promise.resolve().then(() => setBoolean(STORAGE_KEY + permission, true));
|
||||
const setDidAskOnce = (permission: string) => Promise.resolve().then(() => ApplicationSettings.setBoolean(STORAGE_KEY + permission, true));
|
||||
|
||||
const getDidAskOnce = (permission: string) => Promise.resolve(!!getBoolean(STORAGE_KEY + permission));
|
||||
const getDidAskOnce = (permission: string) => Promise.resolve(!!ApplicationSettings.getBoolean(STORAGE_KEY + permission));
|
||||
|
||||
namespace PermissionsAndroid {
|
||||
/**
|
||||
@@ -138,7 +140,7 @@ namespace PermissionsAndroid {
|
||||
* See https://facebook.github.io/react-native/docs/permissionsandroid.html#check
|
||||
*/
|
||||
export async function check(permission: string | string[]) {
|
||||
const context: android.content.Context = androidApp.foregroundActivity || androidApp.startActivity;
|
||||
const context: android.content.Context = getAndroidActivity();
|
||||
let result = true;
|
||||
const granted = android.content.pm.PackageManager.PERMISSION_GRANTED;
|
||||
if (!Array.isArray(permission)) {
|
||||
@@ -188,7 +190,7 @@ namespace PermissionsAndroid {
|
||||
|
||||
let mRequestCode = 0;
|
||||
function requestPermission(permission: string): Promise<PermissionStatus> {
|
||||
const activity: android.app.Activity = androidApp.foregroundActivity || androidApp.startActivity;
|
||||
const activity: android.app.Activity = getAndroidActivity();
|
||||
if (getAndroidSDK() < MARSHMALLOW) {
|
||||
return Promise.resolve(activity.checkPermission(permission, android.os.Process.myPid(), android.os.Process.myUid()) === android.content.pm.PackageManager.PERMISSION_GRANTED ? PermissionsAndroid.RESULTS.GRANTED : PermissionsAndroid.RESULTS.DENIED);
|
||||
}
|
||||
@@ -200,7 +202,7 @@ function requestPermission(permission: string): Promise<PermissionStatus> {
|
||||
try {
|
||||
const requestCode = mRequestCode++;
|
||||
activity.requestPermissions([permission], requestCode);
|
||||
androidApp.on(AndroidApplication.activityRequestPermissionsEvent, (args: AndroidActivityRequestPermissionsEventData) => {
|
||||
Application.android.on(AndroidApplication.activityRequestPermissionsEvent, (args: AndroidActivityRequestPermissionsEventData) => {
|
||||
if (args.requestCode === requestCode) {
|
||||
if (args.grantResults.length > 0) {
|
||||
if (args.grantResults.length > 0 && args.grantResults[0] === android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
@@ -224,22 +226,23 @@ function requestPermission(permission: string): Promise<PermissionStatus> {
|
||||
});
|
||||
}
|
||||
|
||||
async function requestMultiplePermissions(permissions: string[]): Promise<{ [permission: string]: PermissionStatus }> {
|
||||
async function requestMultiplePermissions(permissions: string[], options?: PermissionRequestOptions): Promise<{ [permission: string]: PermissionStatus }> {
|
||||
const grantedPermissions = {};
|
||||
const permissionsToCheck = [];
|
||||
let checkedPermissionsCount = 0;
|
||||
if (Trace.isEnabled()) {
|
||||
Trace.write(`requestMultiplePermissions ${permissions}`, Trace.categories.Permissions, Trace.messageType.info);
|
||||
}
|
||||
const context: android.content.Context = androidApp.foregroundActivity || androidApp.startActivity;
|
||||
const context: android.content.Context = getAndroidActivity();
|
||||
|
||||
for (let i = 0; i < permissions.length; i++) {
|
||||
const perm = permissions[i];
|
||||
const nativePerm = getNativePermissions(perm as PermissionsType, options)[0];
|
||||
|
||||
if (getAndroidSDK() < MARSHMALLOW) {
|
||||
grantedPermissions[perm] = context.checkPermission(perm, android.os.Process.myPid(), android.os.Process.myUid()) === android.content.pm.PackageManager.PERMISSION_GRANTED ? PermissionsAndroid.RESULTS.GRANTED : PermissionsAndroid.RESULTS.DENIED;
|
||||
grantedPermissions[perm] = context.checkPermission(nativePerm, android.os.Process.myPid(), android.os.Process.myUid()) === android.content.pm.PackageManager.PERMISSION_GRANTED ? PermissionsAndroid.RESULTS.GRANTED : PermissionsAndroid.RESULTS.DENIED;
|
||||
checkedPermissionsCount++;
|
||||
} else if (context.checkSelfPermission(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
} else if (context.checkSelfPermission(nativePerm) === android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
grantedPermissions[perm] = PermissionsAndroid.RESULTS.GRANTED;
|
||||
checkedPermissionsCount++;
|
||||
} else {
|
||||
@@ -249,13 +252,13 @@ async function requestMultiplePermissions(permissions: string[]): Promise<{ [per
|
||||
if (permissions.length === checkedPermissionsCount) {
|
||||
return grantedPermissions;
|
||||
}
|
||||
const activity: android.app.Activity = androidApp.foregroundActivity || androidApp.startActivity;
|
||||
const activity: android.app.Activity = getAndroidActivity();
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const requestCode = mRequestCode++;
|
||||
|
||||
activity.requestPermissions(permissionsToCheck, requestCode);
|
||||
androidApp.on(AndroidApplication.activityRequestPermissionsEvent, (args: AndroidActivityRequestPermissionsEventData) => {
|
||||
Application.android.on(AndroidApplication.activityRequestPermissionsEvent, (args: AndroidActivityRequestPermissionsEventData) => {
|
||||
if (args.requestCode === requestCode) {
|
||||
const results = args.grantResults;
|
||||
for (let j = 0; j < permissionsToCheck.length; j++) {
|
||||
@@ -293,7 +296,7 @@ function shouldShowRequestPermissionRationale(permission: string | string[]) {
|
||||
if (getAndroidSDK() < MARSHMALLOW) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
const activity: android.app.Activity = androidApp.foregroundActivity || androidApp.startActivity;
|
||||
const activity: android.app.Activity = getAndroidActivity();
|
||||
try {
|
||||
if (Array.isArray(permission)) {
|
||||
return Promise.resolve(permission.reduce((accu, p) => accu && activity.shouldShowRequestPermissionRationale(p), true));
|
||||
@@ -310,15 +313,15 @@ export class Permissions {
|
||||
}
|
||||
|
||||
static openSettings() {
|
||||
const activity = androidApp.foregroundActivity || androidApp.startActivity;
|
||||
const activity = getAndroidActivity();
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const onActivityResultHandler = (data) => {
|
||||
if (data.requestCode === 5140) {
|
||||
androidApp.off(AndroidApplication.activityResultEvent, onActivityResultHandler);
|
||||
Application.android.off(AndroidApplication.activityResultEvent, onActivityResultHandler);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
androidApp.on(AndroidApplication.activityResultEvent, onActivityResultHandler);
|
||||
Application.android.on(AndroidApplication.activityResultEvent, onActivityResultHandler);
|
||||
const intent = new android.content.Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.setData(android.net.Uri.parse('package:' + activity.getPackageName()));
|
||||
activity.startActivityForResult(intent, 5140);
|
||||
@@ -369,18 +372,18 @@ export class Permissions {
|
||||
let types: string[] = [];
|
||||
if (Array.isArray(permission)) {
|
||||
permission.forEach((s) => {
|
||||
if (s.startsWith('android.permission.')) {
|
||||
types.push(s);
|
||||
} else {
|
||||
types.push(...getNativePermissions(s as PermissionsType, options));
|
||||
}
|
||||
// if (s.startsWith('android.permission.')) {
|
||||
types.push(s);
|
||||
// } else {
|
||||
// types.push(...getNativePermissions(s as PermissionsType, options));
|
||||
// }
|
||||
});
|
||||
} else {
|
||||
if (permission.startsWith('android.permission.')) {
|
||||
types.push(permission);
|
||||
} else {
|
||||
types = getNativePermissions(permission, options);
|
||||
}
|
||||
// if (permission.startsWith('android.permission.')) {
|
||||
types.push(permission);
|
||||
// } else {
|
||||
// types = getNativePermissions(permission, options);
|
||||
// }
|
||||
}
|
||||
if (types.length === 0) {
|
||||
return Promise.resolve([PermissionStatus.authorized, true]);
|
||||
@@ -388,7 +391,7 @@ export class Permissions {
|
||||
|
||||
const rationale = typeof options === 'string' ? undefined : options && options.rationale;
|
||||
if (types.length > 1) {
|
||||
return requestMultiplePermissions(types);
|
||||
return requestMultiplePermissions(types, options);
|
||||
}
|
||||
return PermissionsAndroid.request(types[0], rationale).then((result) => {
|
||||
// PermissionsAndroid.request() to native module resolves to boolean
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PermissionStatus } from './common';
|
||||
export * from './common';
|
||||
export type PermissionsType = 'location' | 'camera' | 'microphone' | 'photo' | 'contacts' | 'event' | 'reminder' | 'bluetooth' | 'bluetoothConnect' | 'bluetoothScan' | 'notification' | 'backgroundRefresh' | 'speechRecognition' | 'mediaLocation' | 'mediaLibrary' | 'motion' | 'storage' | 'callPhone' | 'readSms' | 'receiveSms';
|
||||
export interface PermissionRationale {
|
||||
@@ -9,13 +10,13 @@ export interface PermissionRationale {
|
||||
}
|
||||
export type PermissionCheckOptions = string | { type: string };
|
||||
export type PermissionRequestOptions = string | { type: string; rationale?: PermissionRationale };
|
||||
export type PermissionResult<T> = T extends any[] ? { [k: string]: Status } : [Status, boolean];
|
||||
export type PermissionResult<T> = T extends any[] ? { [k: string]: PermissionStatus } : [PermissionStatus, boolean];
|
||||
|
||||
export class Permissions {
|
||||
static canOpenSettings(): Promise<boolean>;
|
||||
static openSettings(): Promise<boolean>;
|
||||
static getTypes(): Permissions[];
|
||||
static check<T = Permissions>(permission: T, options?: CheckOptions): Promise<PermissionResult<T>>;
|
||||
static request<T = Permissions | Permissions[] | string[]>(permission: T, options?: RequestOptions): Promise<PermissionResult<T>>;
|
||||
static check<T = Permissions>(permission: T, options?: PermissionCheckOptions): Promise<PermissionResult<T>>;
|
||||
static request<T = Permissions | Permissions[] | string[]>(permission: T, options?: PermissionRequestOptions): Promise<PermissionResult<T>>;
|
||||
static checkMultiple<T = Permissions[]>(permissions: T): Promise<PermissionResult<T>>;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Device } from '../platform';
|
||||
import { Trace } from '../trace';
|
||||
import { Device, Trace } from '@nativescript/core';
|
||||
import { PermissionStatus } from './common';
|
||||
import { PermissionCheckOptions, PermissionsType, PermissionRequestOptions } from '.';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@nativescript/permissions",
|
||||
"version": "8.2.0",
|
||||
"description": "A JavaScript library providing an easy to use api for interacting with iOS and Android permission handling.",
|
||||
"description": "Android and iOS permission handling with NativeScript.",
|
||||
"sideEffects": false,
|
||||
"main": "index",
|
||||
"types": "index.d.ts",
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
{
|
||||
"root": "packages/permissions",
|
||||
"sourceRoot": "packages/permissions/src",
|
||||
"sourceRoot": "packages/permissions",
|
||||
"projectType": "library",
|
||||
"targets": {
|
||||
"build": {
|
||||
"executor": "@nrwl/workspace:run-commands",
|
||||
"outputs": ["dist/packages"],
|
||||
"options": {
|
||||
"commands": ["npx rimraf dist/packages/permissions", "./node_modules/.bin/tsc -p packages/permissions/tsconfig.lib.json", "cp packages/permissions/index.d.ts dist/packages/permissions", "cp packages/permissions/package.json dist/packages/permissions", "cp packages/permissions/README.md dist/packages/permissions", "cp LICENSE dist/packages/permissions"],
|
||||
"cwd": ".",
|
||||
"parallel": false
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nrwl/linter:eslint",
|
||||
"outputs": ["{options.outputFile}"],
|
||||
|
||||
3
packages/permissions/references.d.ts
vendored
Normal file
3
packages/permissions/references.d.ts
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/// <reference path="../types-ios/src/lib/ios.d.ts" />
|
||||
/// <reference path="../types-android/src/lib/android-31.d.ts" />
|
||||
/// <reference path="../global-types.d.ts" />
|
||||
@@ -1 +0,0 @@
|
||||
export * from './lib/permissions';
|
||||
@@ -1,16 +1,11 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
],
|
||||
"compilerOptions": {
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
}
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@nativescript/core": ["../core/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["**/*.ts", "./references.d.ts"],
|
||||
"exclude": ["dist", "__tests__"]
|
||||
}
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../dist/out-tsc",
|
||||
"noEmitOnError": true,
|
||||
"noEmitHelpers": true,
|
||||
"declaration": true,
|
||||
"types": []
|
||||
"noImplicitAny": false,
|
||||
"noImplicitUseStrict": true,
|
||||
"removeComments": false,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"diagnostics": true,
|
||||
"sourceMap": true,
|
||||
"inlineSourceMap": false,
|
||||
"baseUrl": ".",
|
||||
"outDir": "../../dist",
|
||||
"types": ["node"],
|
||||
"plugins": [
|
||||
{
|
||||
"transform": "../webpack/transformers/ns-transform-native-classes.ts",
|
||||
"type": "raw"
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": ["**/*.spec.ts"]
|
||||
"exclude": ["**/*.spec.ts", "**/*.test.ts", "dist", "__tests__"],
|
||||
"include": ["**/*.ts", "./references.d.ts"]
|
||||
}
|
||||
|
||||
@@ -104,6 +104,13 @@ module.exports = {
|
||||
description: '@nativescript/core: API Reference Docs Build'
|
||||
}
|
||||
},
|
||||
// @nativescript/permissions
|
||||
'permissions': {
|
||||
build: {
|
||||
script: 'nx run permissions:build',
|
||||
description: '@nativescript/permissions: Build for npm'
|
||||
},
|
||||
},
|
||||
// @nativescript/ui-mobile-base
|
||||
'ui-mobile-base': {
|
||||
build: {
|
||||
@@ -139,6 +146,10 @@ module.exports = {
|
||||
script: 'nx g @nstudio/focus:mode core',
|
||||
description: 'Focus on @nativescript/core'
|
||||
},
|
||||
permissions: {
|
||||
script: 'nx g @nstudio/focus:mode permissions',
|
||||
description: 'Focus on @nativescript/permissions'
|
||||
},
|
||||
types: {
|
||||
script: 'nx g @nstudio/focus:mode types-android,types-ios',
|
||||
description: 'Focus on @nativescript/types'
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"paths": {
|
||||
"@nativescript/core": ["packages/core/index.ts"],
|
||||
"@nativescript/core/*": ["packages/core/*"],
|
||||
"@nativescript/permissions": ["packages/permissions/src/index.ts"],
|
||||
"@nativescript/permissions": ["packages/permissions/index.ts"],
|
||||
"@nativescript/types-android": ["packages/types-android/src/index.ts"],
|
||||
"@nativescript/types-ios": ["packages/types-ios/src/index.ts"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user