permission.uts
3.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { handleError } from "./error.uts";
/**
* 确保已获取指定权限
* @param permissionName 权限名称 (如 "Microphone")
* @param hintText 权限被拒绝时的提示文本
* @returns Promise<boolean> true: 已获取权限, false: 未获取权限
*/
export async function ensurePermission(permissionName: string, hintText: string): Promise<boolean> {
return new Promise((resolve) => {
try {
checkPermission(permissionName, (result) => {
if (result === "granted") {
resolve(true);
} else {
requestPermissions({
names: [permissionName],
success: (res) => {
let granted = false;
// res is string[]
const resList = res as string[];
resList.forEach((v: string) => {
if (v == "granted") {
granted = true;
}
});
if (granted) {
resolve(true);
} else {
uni.showToast({
title: hintText,
icon: "none"
});
resolve(false);
}
},
fail: (err) => {
handleError(err, "PermissionUtils", `请求权限失败 (${permissionName}):`);
resolve(false);
}
});
}
});
} catch (error) {
handleError(error, "PermissionUtils", `检查权限异常 (${permissionName}):`);
resolve(false);
}
});
}
/**
* 确保已获取多个指定权限
* @param permissionNames 权限名称列表
* @param hintText 权限被拒绝时的提示文本
* @returns Promise<boolean> true: 已获取所有权限, false: 未获取权限
*/
export async function ensurePermissions(permissionNames: string[], hintText: string): Promise<boolean> {
if (permissionNames.length === 0) return true;
// 简单实现:逐个检查/请求,或者一次性请求
// 这里的 requestPermissions 似乎支持数组,所以我们可以直接调用 requestPermissions
// 但是 checkPermission 似乎只支持单个 string (根据 index.uts 的签名)
// export function checkPermission(permission: string, complete: (result: string) => void): void
// 如果需要检查多个,可能需要先检查一遍,如果有未授权的,再统一请求
// 简化策略:直接调用 requestPermissions 请求所有,它内部应该会处理已授权的情况?
// 或者我们可以先 check 第一个,如果没授权就请求所有。
// 但 permission-handler-plus 的 requestPermissions 似乎是请求弹窗。
return new Promise((resolve) => {
try {
requestPermissions({
names: permissionNames,
success: (res) => {
let allGranted = true;
const resList = res as string[];
// 假设 resList 顺序对应 permissionNames 或者只是结果列表
// 如果有一个不是 granted,则失败
for (const element of resList) {
if (element != "granted") {
allGranted = false;
break;
}
}
if (allGranted) {
resolve(true);
} else {
uni.showToast({
title: hintText,
icon: "none"
});
resolve(false);
}
},
fail: (err) => {
handleError(err, "PermissionUtils", `请求权限失败 (${permissionNames.join(", ")}):`);
resolve(false);
}
});
} catch (error) {
handleError(error, "PermissionUtils", `请求权限异常 (${permissionNames.join(", ")}):`);
resolve(false);
}
});
}
export async function requestRecordPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> {
return await ensurePermission("Microphone", hintText);
}