@capgo/capacitor-permissions 0.0.0-stage → 8.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js ADDED
@@ -0,0 +1,130 @@
1
+ var capacitorPermissions = (function (exports, core) {
2
+ 'use strict';
3
+
4
+ const Permissions = core.registerPlugin('Permissions', {
5
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.PermissionsWeb()),
6
+ });
7
+
8
+ const QUERY_NAME = {
9
+ camera: 'camera',
10
+ microphone: 'microphone',
11
+ locationWhenInUse: 'geolocation',
12
+ locationAlways: 'geolocation',
13
+ notifications: 'notifications',
14
+ };
15
+ /**
16
+ * Maps browser permission query states to plugin status values.
17
+ */
18
+ function mapPermissionStatus(state) {
19
+ if (state === 'granted') {
20
+ return 'granted';
21
+ }
22
+ if (state === 'denied') {
23
+ return 'blocked';
24
+ }
25
+ if (state === 'prompt' || state === 'prompt-with-rationale') {
26
+ return 'denied';
27
+ }
28
+ return 'unavailable';
29
+ }
30
+ /**
31
+ * Web implementation of the permissions plugin.
32
+ */
33
+ class PermissionsWeb extends core.WebPlugin {
34
+ /** @inheritdoc */
35
+ async check(options) {
36
+ return { status: await this.readStatus(options.permission) };
37
+ }
38
+ /** @inheritdoc */
39
+ async request(options) {
40
+ var _a;
41
+ const { permission } = options;
42
+ try {
43
+ if (permission === 'notifications' && typeof Notification !== 'undefined') {
44
+ const result = await Notification.requestPermission();
45
+ return { status: result === 'granted' ? 'granted' : result === 'denied' ? 'blocked' : 'denied' };
46
+ }
47
+ if ((permission === 'camera' || permission === 'microphone') && ((_a = navigator.mediaDevices) === null || _a === void 0 ? void 0 : _a.getUserMedia)) {
48
+ const stream = await navigator.mediaDevices.getUserMedia({
49
+ video: permission === 'camera',
50
+ audio: permission === 'microphone',
51
+ });
52
+ stream.getTracks().forEach((track) => track.stop());
53
+ return { status: 'granted' };
54
+ }
55
+ if ((permission === 'locationWhenInUse' || permission === 'locationAlways') && navigator.geolocation) {
56
+ await new Promise((resolve, reject) => {
57
+ navigator.geolocation.getCurrentPosition(() => resolve(), (err) => reject(err), { maximumAge: 0, timeout: 10000 });
58
+ });
59
+ return { status: 'granted' };
60
+ }
61
+ }
62
+ catch (_b) {
63
+ return { status: await this.readStatus(permission) };
64
+ }
65
+ return { status: await this.readStatus(permission) };
66
+ }
67
+ /** @inheritdoc */
68
+ async checkMultiple(options) {
69
+ const statuses = {};
70
+ for (const permission of options.permissions) {
71
+ statuses[permission] = await this.readStatus(permission);
72
+ }
73
+ return { statuses };
74
+ }
75
+ /** @inheritdoc */
76
+ async requestMultiple(options) {
77
+ const statuses = {};
78
+ for (const permission of options.permissions) {
79
+ statuses[permission] = (await this.request({ permission })).status;
80
+ }
81
+ return { statuses };
82
+ }
83
+ /** @inheritdoc */
84
+ async shouldShowRationale() {
85
+ return { shouldShow: false };
86
+ }
87
+ /** @inheritdoc */
88
+ async openSettings() {
89
+ throw this.unimplemented('openSettings is not available on web');
90
+ }
91
+ /** @inheritdoc */
92
+ async requestPreciseLocation() {
93
+ return this.request({ permission: 'locationWhenInUse' });
94
+ }
95
+ /** @inheritdoc */
96
+ async getPluginVersion() {
97
+ return { version: 'web' };
98
+ }
99
+ /**
100
+ * Reads the current browser permission state when the Permissions API supports it.
101
+ */
102
+ async readStatus(permission) {
103
+ var _a;
104
+ const queryName = QUERY_NAME[permission];
105
+ if (!queryName || !((_a = navigator.permissions) === null || _a === void 0 ? void 0 : _a.query)) {
106
+ return 'unavailable';
107
+ }
108
+ try {
109
+ const result = await navigator.permissions.query({
110
+ name: queryName,
111
+ });
112
+ return mapPermissionStatus(result.state);
113
+ }
114
+ catch (_b) {
115
+ return 'unavailable';
116
+ }
117
+ }
118
+ }
119
+
120
+ var web = /*#__PURE__*/Object.freeze({
121
+ __proto__: null,
122
+ PermissionsWeb: PermissionsWeb
123
+ });
124
+
125
+ exports.Permissions = Permissions;
126
+
127
+ return exports;
128
+
129
+ })({}, capacitorExports);
130
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Permissions = registerPlugin('Permissions', {\n web: () => import('./web').then((m) => new m.PermissionsWeb()),\n});\nexport * from './definitions';\nexport { Permissions };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nconst QUERY_NAME = {\n camera: 'camera',\n microphone: 'microphone',\n locationWhenInUse: 'geolocation',\n locationAlways: 'geolocation',\n notifications: 'notifications',\n};\n/**\n * Maps browser permission query states to plugin status values.\n */\nfunction mapPermissionStatus(state) {\n if (state === 'granted') {\n return 'granted';\n }\n if (state === 'denied') {\n return 'blocked';\n }\n if (state === 'prompt' || state === 'prompt-with-rationale') {\n return 'denied';\n }\n return 'unavailable';\n}\n/**\n * Web implementation of the permissions plugin.\n */\nexport class PermissionsWeb extends WebPlugin {\n /** @inheritdoc */\n async check(options) {\n return { status: await this.readStatus(options.permission) };\n }\n /** @inheritdoc */\n async request(options) {\n var _a;\n const { permission } = options;\n try {\n if (permission === 'notifications' && typeof Notification !== 'undefined') {\n const result = await Notification.requestPermission();\n return { status: result === 'granted' ? 'granted' : result === 'denied' ? 'blocked' : 'denied' };\n }\n if ((permission === 'camera' || permission === 'microphone') && ((_a = navigator.mediaDevices) === null || _a === void 0 ? void 0 : _a.getUserMedia)) {\n const stream = await navigator.mediaDevices.getUserMedia({\n video: permission === 'camera',\n audio: permission === 'microphone',\n });\n stream.getTracks().forEach((track) => track.stop());\n return { status: 'granted' };\n }\n if ((permission === 'locationWhenInUse' || permission === 'locationAlways') && navigator.geolocation) {\n await new Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(() => resolve(), (err) => reject(err), { maximumAge: 0, timeout: 10000 });\n });\n return { status: 'granted' };\n }\n }\n catch (_b) {\n return { status: await this.readStatus(permission) };\n }\n return { status: await this.readStatus(permission) };\n }\n /** @inheritdoc */\n async checkMultiple(options) {\n const statuses = {};\n for (const permission of options.permissions) {\n statuses[permission] = await this.readStatus(permission);\n }\n return { statuses };\n }\n /** @inheritdoc */\n async requestMultiple(options) {\n const statuses = {};\n for (const permission of options.permissions) {\n statuses[permission] = (await this.request({ permission })).status;\n }\n return { statuses };\n }\n /** @inheritdoc */\n async shouldShowRationale() {\n return { shouldShow: false };\n }\n /** @inheritdoc */\n async openSettings() {\n throw this.unimplemented('openSettings is not available on web');\n }\n /** @inheritdoc */\n async requestPreciseLocation() {\n return this.request({ permission: 'locationWhenInUse' });\n }\n /** @inheritdoc */\n async getPluginVersion() {\n return { version: 'web' };\n }\n /**\n * Reads the current browser permission state when the Permissions API supports it.\n */\n async readStatus(permission) {\n var _a;\n const queryName = QUERY_NAME[permission];\n if (!queryName || !((_a = navigator.permissions) === null || _a === void 0 ? void 0 : _a.query)) {\n return 'unavailable';\n }\n try {\n const result = await navigator.permissions.query({\n name: queryName,\n });\n return mapPermissionStatus(result.state);\n }\n catch (_b) {\n return 'unavailable';\n }\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;AACK,UAAC,WAAW,GAAGA,mBAAc,CAAC,aAAa,EAAE;IAClD,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,cAAc,EAAE,CAAC;IAClE,CAAC;;ICFD,MAAM,UAAU,GAAG;IACnB,IAAI,MAAM,EAAE,QAAQ;IACpB,IAAI,UAAU,EAAE,YAAY;IAC5B,IAAI,iBAAiB,EAAE,aAAa;IACpC,IAAI,cAAc,EAAE,aAAa;IACjC,IAAI,aAAa,EAAE,eAAe;IAClC,CAAC;IACD;IACA;IACA;IACA,SAAS,mBAAmB,CAAC,KAAK,EAAE;IACpC,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;IAC7B,QAAQ,OAAO,SAAS;IACxB,IAAI;IACJ,IAAI,IAAI,KAAK,KAAK,Q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B,YAAY,OAAO,aAAa;IAChC,QAAQ;IACR,IAAI;IACJ;;;;;;;;;;;;;;;"}
@@ -0,0 +1,139 @@
1
+ import Foundation
2
+ import AVFoundation
3
+ import Photos
4
+ import Contacts
5
+ import EventKit
6
+ import CoreBluetooth
7
+ import CoreMotion
8
+ import Speech
9
+ import AppTrackingTransparency
10
+ import CoreLocation
11
+ import UserNotifications
12
+
13
+ public enum PermissionStatusValue: String {
14
+ case granted
15
+ case denied
16
+ case blocked
17
+ case limited
18
+ case unavailable
19
+ }
20
+
21
+ enum PermissionStatusMapper {
22
+ static func fromPhoto(_ status: PHAuthorizationStatus) -> PermissionStatusValue {
23
+ switch status {
24
+ case .authorized: return .granted
25
+ case .limited: return .limited
26
+ case .denied: return .denied
27
+ case .restricted: return .blocked
28
+ case .notDetermined: return .denied
29
+ @unknown default: return .unavailable
30
+ }
31
+ }
32
+
33
+ static func fromContacts(_ status: CNAuthorizationStatus) -> PermissionStatusValue {
34
+ switch status {
35
+ case .authorized: return .granted
36
+ case .denied: return .denied
37
+ case .restricted: return .blocked
38
+ case .notDetermined: return .denied
39
+ default:
40
+ if #available(iOS 18.0, *), status == .limited {
41
+ return .limited
42
+ }
43
+ return .unavailable
44
+ }
45
+ }
46
+
47
+ static func fromEventKit(_ status: EKAuthorizationStatus) -> PermissionStatusValue {
48
+ if #available(iOS 17.0, *) {
49
+ switch status {
50
+ case .fullAccess: return .granted
51
+ case .writeOnly: return .limited
52
+ case .denied: return .denied
53
+ case .restricted: return .blocked
54
+ case .notDetermined: return .denied
55
+ @unknown default: return .unavailable
56
+ }
57
+ }
58
+ switch status {
59
+ case .authorized: return .granted
60
+ case .denied: return .denied
61
+ case .restricted: return .blocked
62
+ case .notDetermined: return .denied
63
+ default: return .unavailable
64
+ }
65
+ }
66
+
67
+ static func fromAV(_ status: AVAuthorizationStatus) -> PermissionStatusValue {
68
+ switch status {
69
+ case .authorized: return .granted
70
+ case .denied: return .denied
71
+ case .restricted: return .blocked
72
+ case .notDetermined: return .denied
73
+ @unknown default: return .unavailable
74
+ }
75
+ }
76
+
77
+ static func fromTracking(_ status: ATTrackingManager.AuthorizationStatus) -> PermissionStatusValue {
78
+ switch status {
79
+ case .authorized: return .granted
80
+ case .denied: return .denied
81
+ case .restricted: return .blocked
82
+ case .notDetermined: return .denied
83
+ @unknown default: return .unavailable
84
+ }
85
+ }
86
+
87
+ static func fromSpeech(_ status: SFSpeechRecognizerAuthorizationStatus) -> PermissionStatusValue {
88
+ switch status {
89
+ case .authorized: return .granted
90
+ case .denied: return .denied
91
+ case .restricted: return .blocked
92
+ case .notDetermined: return .denied
93
+ @unknown default: return .unavailable
94
+ }
95
+ }
96
+
97
+ static func fromBluetooth(_ status: CBManagerAuthorization) -> PermissionStatusValue {
98
+ switch status {
99
+ case .allowedAlways: return .granted
100
+ case .denied: return .denied
101
+ case .restricted: return .blocked
102
+ case .notDetermined: return .denied
103
+ @unknown default: return .unavailable
104
+ }
105
+ }
106
+
107
+ static func fromMotion(_ status: CMAuthorizationStatus) -> PermissionStatusValue {
108
+ switch status {
109
+ case .authorized: return .granted
110
+ case .denied: return .denied
111
+ case .restricted: return .blocked
112
+ case .notDetermined: return .denied
113
+ @unknown default: return .unavailable
114
+ }
115
+ }
116
+
117
+ static func fromLocation(
118
+ _ status: CLAuthorizationStatus,
119
+ accuracy: CLAccuracyAuthorization?
120
+ ) -> PermissionStatusValue {
121
+ switch status {
122
+ case .authorizedAlways, .authorizedWhenInUse:
123
+ return accuracy == .reducedAccuracy ? .limited : .granted
124
+ case .denied: return .denied
125
+ case .restricted: return .blocked
126
+ case .notDetermined: return .denied
127
+ @unknown default: return .unavailable
128
+ }
129
+ }
130
+
131
+ static func fromNotifications(_ settings: UNNotificationSettings) -> PermissionStatusValue {
132
+ switch settings.authorizationStatus {
133
+ case .authorized, .provisional, .ephemeral: return .granted
134
+ case .denied: return .denied
135
+ case .notDetermined: return .denied
136
+ @unknown default: return .unavailable
137
+ }
138
+ }
139
+ }
@@ -0,0 +1,222 @@
1
+ import Foundation
2
+ import AVFoundation
3
+ import Photos
4
+ import Contacts
5
+ import EventKit
6
+ import CoreLocation
7
+ import CoreBluetooth
8
+ import CoreMotion
9
+ import UserNotifications
10
+ import Speech
11
+ import AppTrackingTransparency
12
+
13
+ @objc public class Permissions: NSObject, CLLocationManagerDelegate {
14
+ private let locationManager = CLLocationManager()
15
+ private var locationContinuation: ((PermissionStatusValue) -> Void)?
16
+ private var preciseContinuation: ((PermissionStatusValue) -> Void)?
17
+
18
+ override public init() {
19
+ super.init()
20
+ locationManager.delegate = self
21
+ }
22
+
23
+ @objc public func getPluginVersion() -> String {
24
+ return "native"
25
+ }
26
+
27
+ public func check(_ name: String, completion: @escaping (PermissionStatusValue) -> Void) {
28
+ switch name {
29
+ case "camera":
30
+ completion(PermissionStatusMapper.fromAV(AVCaptureDevice.authorizationStatus(for: .video)))
31
+ case "microphone":
32
+ completion(PermissionStatusMapper.fromAV(AVCaptureDevice.authorizationStatus(for: .audio)))
33
+ case "photoLibrary":
34
+ completion(PermissionStatusMapper.fromPhoto(PHPhotoLibrary.authorizationStatus(for: .readWrite)))
35
+ case "photoLibraryAddOnly":
36
+ completion(PermissionStatusMapper.fromPhoto(PHPhotoLibrary.authorizationStatus(for: .addOnly)))
37
+ case "contacts":
38
+ completion(PermissionStatusMapper.fromContacts(CNContactStore.authorizationStatus(for: .contacts)))
39
+ case "calendar":
40
+ completion(PermissionStatusMapper.fromEventKit(EKEventStore.authorizationStatus(for: .event)))
41
+ case "reminders":
42
+ completion(PermissionStatusMapper.fromEventKit(EKEventStore.authorizationStatus(for: .reminder)))
43
+ case "locationWhenInUse", "locationAlways":
44
+ completion(checkLocation(name))
45
+ case "bluetooth":
46
+ completion(PermissionStatusMapper.fromBluetooth(CBManager.authorization))
47
+ case "motion":
48
+ completion(checkMotion())
49
+ case "notifications":
50
+ UNUserNotificationCenter.current().getNotificationSettings { settings in
51
+ completion(PermissionStatusMapper.fromNotifications(settings))
52
+ }
53
+ case "speechRecognition":
54
+ completion(PermissionStatusMapper.fromSpeech(SFSpeechRecognizer.authorizationStatus()))
55
+ case "appTrackingTransparency":
56
+ completion(PermissionStatusMapper.fromTracking(ATTrackingManager.trackingAuthorizationStatus))
57
+ default:
58
+ completion(.unavailable)
59
+ }
60
+ }
61
+
62
+ public func request(_ name: String, completion: @escaping (PermissionStatusValue) -> Void) {
63
+ switch name {
64
+ case "camera":
65
+ AVCaptureDevice.requestAccess(for: .video) { _ in self.check(name, completion: completion) }
66
+ case "microphone":
67
+ AVCaptureDevice.requestAccess(for: .audio) { _ in self.check(name, completion: completion) }
68
+ case "photoLibrary":
69
+ PHPhotoLibrary.requestAuthorization(for: .readWrite) { _ in
70
+ self.check(name, completion: completion)
71
+ }
72
+ case "photoLibraryAddOnly":
73
+ PHPhotoLibrary.requestAuthorization(for: .addOnly) { _ in
74
+ self.check(name, completion: completion)
75
+ }
76
+ case "contacts":
77
+ CNContactStore().requestAccess(for: .contacts) { _, _ in
78
+ self.check(name, completion: completion)
79
+ }
80
+ case "calendar":
81
+ requestCalendar(completion)
82
+ case "reminders":
83
+ requestReminders(completion)
84
+ case "locationWhenInUse":
85
+ requestLocation(always: false, completion: completion)
86
+ case "locationAlways":
87
+ requestLocation(always: true, completion: completion)
88
+ case "bluetooth":
89
+ requestBluetooth(completion)
90
+ case "motion":
91
+ requestMotion(completion)
92
+ case "notifications":
93
+ UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in
94
+ self.check(name, completion: completion)
95
+ }
96
+ case "speechRecognition":
97
+ SFSpeechRecognizer.requestAuthorization { _ in self.check(name, completion: completion) }
98
+ case "appTrackingTransparency":
99
+ ATTrackingManager.requestTrackingAuthorization { _ in
100
+ self.check(name, completion: completion)
101
+ }
102
+ default:
103
+ check(name, completion: completion)
104
+ }
105
+ }
106
+
107
+ public func requestPreciseLocation(completion: @escaping (PermissionStatusValue) -> Void) {
108
+ let status = locationManager.authorizationStatus
109
+ guard status == .authorizedWhenInUse || status == .authorizedAlways else {
110
+ completion(PermissionStatusMapper.fromLocation(
111
+ status,
112
+ accuracy: locationManager.accuracyAuthorization
113
+ ))
114
+ return
115
+ }
116
+ if locationManager.accuracyAuthorization == .fullAccuracy {
117
+ completion(.granted)
118
+ return
119
+ }
120
+ preciseContinuation = completion
121
+ locationManager.requestTemporaryFullAccuracyAuthorization(withPurposeKey: "PreciseLocation") { _ in
122
+ let cont = self.preciseContinuation
123
+ self.preciseContinuation = nil
124
+ cont?(PermissionStatusMapper.fromLocation(
125
+ self.locationManager.authorizationStatus,
126
+ accuracy: self.locationManager.accuracyAuthorization
127
+ ))
128
+ }
129
+ }
130
+
131
+ public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
132
+ if let cont = locationContinuation {
133
+ locationContinuation = nil
134
+ let name = manager.authorizationStatus == .authorizedAlways
135
+ ? "locationAlways"
136
+ : "locationWhenInUse"
137
+ check(name, completion: cont)
138
+ }
139
+ }
140
+
141
+ private func checkLocation(_ name: String) -> PermissionStatusValue {
142
+ let status = locationManager.authorizationStatus
143
+ let accuracy = locationManager.accuracyAuthorization
144
+ if name == "locationAlways" {
145
+ if status == .authorizedAlways {
146
+ return accuracy == .reducedAccuracy ? .limited : .granted
147
+ }
148
+ if status == .authorizedWhenInUse {
149
+ return .denied
150
+ }
151
+ }
152
+ return PermissionStatusMapper.fromLocation(status, accuracy: accuracy)
153
+ }
154
+
155
+ private func checkMotion() -> PermissionStatusValue {
156
+ if CMMotionActivityManager.isActivityAvailable() {
157
+ return PermissionStatusMapper.fromMotion(CMMotionActivityManager.authorizationStatus())
158
+ }
159
+ if CMPedometer.isPedometerEventTrackingAvailable() {
160
+ return PermissionStatusMapper.fromMotion(CMPedometer.authorizationStatus())
161
+ }
162
+ return .unavailable
163
+ }
164
+
165
+ private func requestCalendar(_ completion: @escaping (PermissionStatusValue) -> Void) {
166
+ let store = EKEventStore()
167
+ if #available(iOS 17.0, *) {
168
+ store.requestFullAccessToEvents { _, _ in
169
+ self.check("calendar", completion: completion)
170
+ }
171
+ } else {
172
+ store.requestAccess(to: .event) { _, _ in
173
+ self.check("calendar", completion: completion)
174
+ }
175
+ }
176
+ }
177
+
178
+ private func requestReminders(_ completion: @escaping (PermissionStatusValue) -> Void) {
179
+ let store = EKEventStore()
180
+ if #available(iOS 17.0, *) {
181
+ store.requestFullAccessToReminders { _, _ in
182
+ self.check("reminders", completion: completion)
183
+ }
184
+ } else {
185
+ store.requestAccess(to: .reminder) { _, _ in
186
+ self.check("reminders", completion: completion)
187
+ }
188
+ }
189
+ }
190
+
191
+ private func requestLocation(always: Bool, completion: @escaping (PermissionStatusValue) -> Void) {
192
+ locationContinuation = completion
193
+ if always {
194
+ locationManager.requestAlwaysAuthorization()
195
+ } else {
196
+ locationManager.requestWhenInUseAuthorization()
197
+ }
198
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
199
+ if let cont = self.locationContinuation {
200
+ self.locationContinuation = nil
201
+ self.check(always ? "locationAlways" : "locationWhenInUse", completion: cont)
202
+ }
203
+ }
204
+ }
205
+
206
+ private func requestBluetooth(_ completion: @escaping (PermissionStatusValue) -> Void) {
207
+ _ = CBCentralManager(delegate: nil, queue: nil, options: [
208
+ CBCentralManagerOptionShowPowerAlertKey: false
209
+ ])
210
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
211
+ self.check("bluetooth", completion: completion)
212
+ }
213
+ }
214
+
215
+ private func requestMotion(_ completion: @escaping (PermissionStatusValue) -> Void) {
216
+ let manager = CMMotionActivityManager()
217
+ let now = Date()
218
+ manager.queryActivityStarting(from: now, to: now, to: .main) { _, _ in
219
+ self.check("motion", completion: completion)
220
+ }
221
+ }
222
+ }
@@ -0,0 +1,123 @@
1
+ import Foundation
2
+ import Capacitor
3
+ import UIKit
4
+
5
+ @objc(PermissionsPlugin)
6
+ public class PermissionsPlugin: CAPPlugin, CAPBridgedPlugin {
7
+ public let identifier = "PermissionsPlugin"
8
+ public let jsName = "Permissions"
9
+ public let pluginMethods: [CAPPluginMethod] = [
10
+ CAPPluginMethod(name: "check", returnType: CAPPluginReturnPromise),
11
+ CAPPluginMethod(name: "request", returnType: CAPPluginReturnPromise),
12
+ CAPPluginMethod(name: "checkMultiple", returnType: CAPPluginReturnPromise),
13
+ CAPPluginMethod(name: "requestMultiple", returnType: CAPPluginReturnPromise),
14
+ CAPPluginMethod(name: "shouldShowRationale", returnType: CAPPluginReturnPromise),
15
+ CAPPluginMethod(name: "openSettings", returnType: CAPPluginReturnPromise),
16
+ CAPPluginMethod(name: "requestPreciseLocation", returnType: CAPPluginReturnPromise),
17
+ CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise)
18
+ ]
19
+
20
+ private let implementation = Permissions()
21
+
22
+ @objc func check(_ call: CAPPluginCall) {
23
+ guard let permission = call.getString("permission") else {
24
+ call.reject("permission is required")
25
+ return
26
+ }
27
+ implementation.check(permission) { status in
28
+ call.resolve(["status": status.rawValue])
29
+ }
30
+ }
31
+
32
+ @objc func request(_ call: CAPPluginCall) {
33
+ guard let permission = call.getString("permission") else {
34
+ call.reject("permission is required")
35
+ return
36
+ }
37
+ implementation.request(permission) { status in
38
+ call.resolve(["status": status.rawValue])
39
+ }
40
+ }
41
+
42
+ @objc func checkMultiple(_ call: CAPPluginCall) {
43
+ guard let permissions = call.getArray("permissions", String.self), !permissions.isEmpty else {
44
+ call.reject("permissions is required")
45
+ return
46
+ }
47
+ var statuses: [String: String] = [:]
48
+ let group = DispatchGroup()
49
+ for permission in permissions {
50
+ group.enter()
51
+ implementation.check(permission) { status in
52
+ statuses[permission] = status.rawValue
53
+ group.leave()
54
+ }
55
+ }
56
+ group.notify(queue: .main) {
57
+ call.resolve(["statuses": statuses])
58
+ }
59
+ }
60
+
61
+ @objc func requestMultiple(_ call: CAPPluginCall) {
62
+ guard let permissions = call.getArray("permissions", String.self), !permissions.isEmpty else {
63
+ call.reject("permissions is required")
64
+ return
65
+ }
66
+ var statuses: [String: String] = [:]
67
+ func next(_ index: Int) {
68
+ if index >= permissions.count {
69
+ call.resolve(["statuses": statuses])
70
+ return
71
+ }
72
+ let permission = permissions[index]
73
+ implementation.request(permission) { status in
74
+ statuses[permission] = status.rawValue
75
+ next(index + 1)
76
+ }
77
+ }
78
+ next(0)
79
+ }
80
+
81
+ @objc func shouldShowRationale(_ call: CAPPluginCall) {
82
+ call.resolve(["shouldShow": false])
83
+ }
84
+
85
+ @objc func openSettings(_ call: CAPPluginCall) {
86
+ let type = call.getString("type") ?? "application"
87
+ DispatchQueue.main.async {
88
+ let url: URL?
89
+ if type == "notifications" {
90
+ if #available(iOS 16.0, *) {
91
+ url = URL(string: UIApplication.openNotificationSettingsURLString)
92
+ } else {
93
+ url = URL(string: UIApplication.openSettingsURLString)
94
+ }
95
+ } else {
96
+ url = URL(string: UIApplication.openSettingsURLString)
97
+ }
98
+ guard let url else {
99
+ call.reject("Unable to open settings")
100
+ return
101
+ }
102
+ UIApplication.shared.open(url, options: [:]) { success in
103
+ if success {
104
+ call.resolve()
105
+ } else {
106
+ call.reject("Unable to open settings")
107
+ }
108
+ }
109
+ }
110
+ }
111
+
112
+ @objc func requestPreciseLocation(_ call: CAPPluginCall) {
113
+ implementation.requestPreciseLocation { status in
114
+ call.resolve(["status": status.rawValue])
115
+ }
116
+ }
117
+
118
+ @objc func getPluginVersion(_ call: CAPPluginCall) {
119
+ call.resolve([
120
+ "version": implementation.getPluginVersion()
121
+ ])
122
+ }
123
+ }