Skip to content

Commit 67fe2d8

Browse files
committed
Add Permission.check()
1 parent 9dcd2c3 commit 67fe2d8

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//
2+
// Permission+Check.swift
3+
// AndroidKit
4+
//
5+
// Created by Alsey Coleman Miller on 2/26/26.
6+
//
7+
8+
#if os(Android)
9+
import Android
10+
import AndroidNDK
11+
#elseif canImport(Darwin)
12+
import Darwin
13+
#elseif canImport(Glibc)
14+
import Glibc
15+
#endif
16+
import SystemPackage
17+
18+
public extension Permission {
19+
20+
/// Result of `APermissionManager_checkPermission`.
21+
enum CheckStatus: Sendable, Equatable {
22+
/// Permission is granted (`0`).
23+
case granted
24+
/// Permission is denied (`-1`).
25+
case denied
26+
/// Any other platform-specific status code.
27+
case unknown(Int32)
28+
}
29+
}
30+
31+
public extension Permission {
32+
33+
/// Checks this permission for a specific process/user pair using
34+
/// `APermissionManager_checkPermission`.
35+
///
36+
/// - Parameters:
37+
/// - pid: Process ID to evaluate. Defaults to the current process ID.
38+
/// - uid: User ID to evaluate. Defaults to the current user ID.
39+
/// - Returns: Permission check status.
40+
func check(
41+
pid: pid_t = getpid(),
42+
uid: uid_t = getuid()
43+
) -> CheckStatus {
44+
let result: Int32
45+
#if os(Android)
46+
result = rawValue.withCString {
47+
APermissionManager_checkPermission($0, pid, uid)
48+
}
49+
#else
50+
result = -1
51+
#endif
52+
switch result {
53+
case 0:
54+
return .granted
55+
case -1:
56+
return .denied
57+
default:
58+
return .unknown(result)
59+
}
60+
}
61+
62+
/// Returns `true` when this permission is granted for the current process.
63+
var isGranted: Bool {
64+
check() == .granted
65+
}
66+
}

0 commit comments

Comments
 (0)