• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Persisting Temporary Permissions (ArkTS)
2
3## When to Use
4
5If an application accesses a file by using Picker, the permission for accessing the file will be automatically invalidated after the application exits or the device restarts. To retain the permission for accessing the file, you need to persist the temporarily granted permission.
6
7## Persisting a Temporary Permission Granted by Picker
8
9You can use Picker to select a file or folder, and persist the temporary permission granted by Picker by using the API provided by [ohos.fileshare](../reference/apis-core-file-kit/js-apis-fileShare.md).
10
111. When an application needs to temporarily access data in a user directory, for example, a communication application needs to send a user file or image, it calls [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) of Picker to select the file or image to be sent. In this case, the application obtains the temporary permission for accessing the file or image. After the application or device is restarted, the application still needs to call a Picker API to access the file or image.
12
132. Sometimes, an application needs to access a file or folder multiple times. For example, after editing a user file, a file editor application needs to select and open the file directly from the history records. In this case, you can use Picker to select the file, and use [ohos.fileshare.persistPermission](../reference/apis-core-file-kit/js-apis-fileShare.md#filesharepersistpermission11) to persist the temporary permission granted by Picker.
14
15Before persisting a temporary permission, ensure that:<br>The device must have the system capability SystemCapability.FileManagement.AppFileService.FolderAuthorization. You can use **canIUse()** to check whether the device has the required system capability.
16
17```ts
18if (!canIUse('SystemCapability.FileManagement.AppFileService.FolderAuthorization')) {
19    console.error('this api is not supported on this device');
20    return;
21}
22```
23
24**Required Permissions**<br>
25ohos.permission.FILE_ACCESS_PERSIST. For details about how to request the permission, see [Workflow for Requesting Permissions](../security/AccessToken/determine-application-mode.md).
26
27**Example**
28
29```ts
30import { BusinessError } from '@kit.BasicServicesKit';
31import { picker } from '@kit.CoreFileKit';
32import { fileShare } from '@kit.CoreFileKit';
33
34async function persistPermissionExample() {
35    try {
36        let DocumentSelectOptions = new picker.DocumentSelectOptions();
37        let documentPicker = new picker.DocumentViewPicker();
38        let uris = await documentPicker.select(DocumentSelectOptions);
39        let policyInfo: fileShare.PolicyInfo = {
40            uri: uris[0],
41            operationMode: fileShare.OperationMode.READ_MODE,
42        };
43        let policies: Array<fileShare.PolicyInfo> = [policyInfo];
44        fileShare.persistPermission(policies).then(() => {
45            console.info("persistPermission successfully");
46        }).catch((err: BusinessError<Array<fileShare.PolicyErrorResult>>) => {
47            console.error("persistPermission failed with error message: " + err.message + ", error code: " + err.code);
48            if (err.code == 13900001 && err.data) {
49                for (let i = 0; i < err.data.length; i++) {
50                    console.error("error code : " + JSON.stringify(err.data[i].code));
51                    console.error("error uri : " + JSON.stringify(err.data[i].uri));
52                    console.error("error reason : " + JSON.stringify(err.data[i].message));
53                }
54            }
55        });
56    } catch (error) {
57        let err: BusinessError = error as BusinessError;
58        console.error('persistPermission failed with err: ' + JSON.stringify(err));
59    }
60}
61```
62
63**NOTE**
64>
65> - You are advised to save the URI of the file with persistent permission for the related application locally to facilitate the subsequent activation.
66> - The permission persistence data is also stored in the system database. After the application or device is restarted, the persistent permission can be used only after being activated. For details, see [Activating a Persistent Permission](#activating-a-persistent-permission-for-accessing-a-file-or-folder).
67> - The APIs used for persisting permissions are available only for 2-in-1 devices. You can use **canIUse()** to check whether the device has the required system capability. The caller must also have the required permissions.
68> - When an application is uninstalled, all the permission authorization data will be deleted. After the application is reinstalled, re-authorization is required.
69
70For details about how to persist a temporary permission using C/C++ APIs, see [OH_FileShare_PersistPermission](native-fileshare-guidelines.md).
71
72You can use [ohos.fileshare.revokePermission](../reference/apis-core-file-kit/js-apis-fileShare.md#filesharerevokepermission11) to revoke the persistent permission from a file, and update the data stored in the application to delete the file URI from the recently accessed data.
73
74**Required Permissions**
75ohos.permission.FILE_ACCESS_PERSIST. For details about how to request the permission, see [Workflow for Requesting Permissions](../security/AccessToken/determine-application-mode.md).
76
77**Example**
78
79```ts
80import { BusinessError } from '@kit.BasicServicesKit';
81import { picker } from '@kit.CoreFileKit';
82import { fileShare } from '@kit.CoreFileKit';
83
84async function revokePermissionExample() {
85    try {
86        let uri = "file://docs/storage/Users/username/tmp.txt";
87        let policyInfo: fileShare.PolicyInfo = {
88            uri: uri,
89            operationMode: fileShare.OperationMode.READ_MODE,
90        };
91        let policies: Array<fileShare.PolicyInfo> = [policyInfo];
92        fileShare.revokePermission(policies).then(() => {
93            console.info("revokePermission successfully");
94        }).catch((err: BusinessError<Array<fileShare.PolicyErrorResult>>) => {
95            console.error("revokePermission failed with error message: " + err.message + ", error code: " + err.code);
96            if (err.code == 13900001 && err.data) {
97                for (let i = 0; i < err.data.length; i++) {
98                    console.error("error code : " + JSON.stringify(err.data[i].code));
99                    console.error("error uri : " + JSON.stringify(err.data[i].uri));
100                    console.error("error reason : " + JSON.stringify(err.data[i].message));
101                }
102            }
103        });
104    } catch (error) {
105        let err: BusinessError = error as BusinessError;
106        console.error('revokePermission failed with err: ' + JSON.stringify(err));
107    }
108}
109```
110
111**NOTE**
112>
113> - The URI in the example comes from the permission persistence data stored for the application.
114> - You are advised to activate the persistent permissions based on service requirements. Do not activate all persistent permissions.
115> - The APIs used for persisting permissions are available only for 2-in-1 devices. You can use **canIUse()** to check whether the device has the required system capability. The caller must also have the required permissions.
116
117For details about how to revoke a persistent permission using C/C++ APIs, see [OH_FileShare_RevokePermission](native-fileshare-guidelines.md).
118
119## Activating a Persistent Permission for Accessing a File or Folder
120
121Each time an application is started, its persistent permissions have not been loaded to the memory. To make a persistent permission still valid after the application is restarted, use [ohos.fileshare.activatePermission](../reference/apis-core-file-kit/js-apis-fileShare.md#fileshareactivatepermission11) to activate the permission.
122
123**Required Permissions**
124ohos.permission.FILE_ACCESS_PERSIST. For details about how to request the permission, see [Workflow for Requesting Permissions](../security/AccessToken/determine-application-mode.md).
125
126**Example**
127
128```ts
129import { BusinessError } from '@kit.BasicServicesKit';
130import { picker } from '@kit.CoreFileKit';
131import { fileShare } from '@kit.CoreFileKit';
132
133async function activatePermissionExample() {
134    try {
135        let uri = "file://docs/storage/Users/username/tmp.txt";
136        let policyInfo: fileShare.PolicyInfo = {
137            uri: uri,
138            operationMode: fileShare.OperationMode.READ_MODE,
139        };
140        let policies: Array<fileShare.PolicyInfo> = [policyInfo];
141        fileShare.activatePermission(policies).then(() => {
142            console.info("activatePermission successfully");
143        }).catch((err: BusinessError<Array<fileShare.PolicyErrorResult>>) => {
144            console.error("activatePermission failed with error message: " + err.message + ", error code: " + err.code);
145            if (err.code == 13900001 && err.data) {
146                for (let i = 0; i < err.data.length; i++) {
147                    console.error("error code : " + JSON.stringify(err.data[i].code));
148                    console.error("error uri : " + JSON.stringify(err.data[i].uri));
149                    console.error("error reason : " + JSON.stringify(err.data[i].message));
150                    if (err.data[i].code == fileShare.PolicyErrorCode.PERMISSION_NOT_PERSISTED) {
151                        // Persist the permission for a file or folder and then activate it.
152                    }
153                }
154            }
155        });
156    } catch (error) {
157        let err: BusinessError = error as BusinessError;
158        console.error('activatePermission failed with err: ' + JSON.stringify(err));
159    }
160}
161```
162
163**NOTE**
164>
165> - The URI in the example comes from the permission persistence data stored for the application.
166> - You are advised to activate the persistent permissions based on service requirements. Do not activate all persistent permissions.
167> - If the activation fails because the permission has not been persisted, persist the permission first.
168> - The APIs used for persisting permissions are available only for 2-in-1 devices. You can use **canIUse()** to check whether the device has the required system capability. The caller must also have the required permissions.
169
170For details about how to activate a persistent permission using C/C++ APIs, see [OH_FileShare_ActivatePermission](native-fileshare-guidelines.md).
171