-
Notifications
You must be signed in to change notification settings - Fork 673
Expand file tree
/
Copy pathPushNotificationsPlugin.swift
More file actions
231 lines (201 loc) · 8.43 KB
/
PushNotificationsPlugin.swift
File metadata and controls
231 lines (201 loc) · 8.43 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import Foundation
import Capacitor
import UserNotifications
enum PushNotificationError: Error {
case tokenParsingFailed
case tokenRegistrationFailed
}
enum PushNotificationsPermissions: String {
case prompt
case denied
case granted
}
@objc(PushNotificationsPlugin)
public class PushNotificationsPlugin: CAPPlugin, CAPBridgedPlugin {
public let identifier = "PushNotificationsPlugin"
public let jsName = "PushNotifications"
public let pluginMethods: [CAPPluginMethod] = [
CAPPluginMethod(name: "register", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "unregister", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "checkPermissions", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "requestPermissions", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "getDeliveredNotifications", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "removeAllDeliveredNotifications", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "removeDeliveredNotifications", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "createChannel", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "listChannels", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "deleteChannel", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "openSettings", returnType: CAPPluginReturnPromise),
]
private let notificationDelegateHandler = PushNotificationsHandler()
private var appDelegateRegistrationCalled: Bool = false
override public func load() {
self.bridge?.notificationRouter.pushNotificationHandler = self.notificationDelegateHandler
self.notificationDelegateHandler.plugin = self
NotificationCenter.default.addObserver(self,
selector: #selector(self.didRegisterForRemoteNotificationsWithDeviceToken(notification:)),
name: .capacitorDidRegisterForRemoteNotifications,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(self.didFailToRegisterForRemoteNotificationsWithError(notification:)),
name: .capacitorDidFailToRegisterForRemoteNotifications,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/**
* Register for push notifications
*/
@objc func register(_ call: CAPPluginCall) {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
call.resolve()
}
/**
* Unregister for remote notifications
*/
@objc func unregister(_ call: CAPPluginCall) {
DispatchQueue.main.async {
UIApplication.shared.unregisterForRemoteNotifications()
call.resolve()
}
}
/**
* Request notification permission
*/
@objc override public func requestPermissions(_ call: CAPPluginCall) {
self.notificationDelegateHandler.requestPermissions { granted, error in
guard error == nil else {
if let err = error {
call.reject(err.localizedDescription)
return
}
call.reject("unknown error in permissions request")
return
}
var result: PushNotificationsPermissions = .denied
if granted {
result = .granted
}
call.resolve(["receive": result.rawValue])
}
}
/**
* Check notification permission
*/
@objc override public func checkPermissions(_ call: CAPPluginCall) {
self.notificationDelegateHandler.checkPermissions { status in
var result: PushNotificationsPermissions = .prompt
switch status {
case .notDetermined:
result = .prompt
case .denied:
result = .denied
case .ephemeral, .authorized, .provisional:
result = .granted
@unknown default:
result = .prompt
}
call.resolve(["receive": result.rawValue])
}
}
/**
* Get notifications in Notification Center
*/
@objc func getDeliveredNotifications(_ call: CAPPluginCall) {
if !appDelegateRegistrationCalled {
call.reject("event capacitorDidRegisterForRemoteNotifications not called. Visit https://capacitorjs.com/docs/apis/push-notifications for more information")
return
}
UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: { (notifications) in
let ret = notifications.map({ (notification) -> [String: Any] in
return self.notificationDelegateHandler.makeNotificationRequestJSObject(notification.request)
})
call.resolve([
"notifications": ret
])
})
}
/**
* Remove specified notifications from Notification Center
*/
@objc func removeDeliveredNotifications(_ call: CAPPluginCall) {
if !appDelegateRegistrationCalled {
call.reject("event capacitorDidRegisterForRemoteNotifications not called. Visit https://capacitorjs.com/docs/apis/push-notifications for more information")
return
}
guard let notifications = call.getArray("notifications", JSObject.self) else {
call.reject("Must supply notifications to remove")
return
}
let ids = notifications.map { $0["id"] as? String ?? "" }
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ids)
call.resolve()
}
/**
* Remove all notifications from Notification Center
*/
@objc func removeAllDeliveredNotifications(_ call: CAPPluginCall) {
if !appDelegateRegistrationCalled {
call.reject("event capacitorDidRegisterForRemoteNotifications not called. Visit https://capacitorjs.com/docs/apis/push-notifications for more information")
return
}
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
DispatchQueue.main.async(execute: {
UIApplication.shared.applicationIconBadgeNumber = 0
})
call.resolve()
}
@objc func createChannel(_ call: CAPPluginCall) {
call.unimplemented("Not available on iOS")
}
@objc func deleteChannel(_ call: CAPPluginCall) {
call.unimplemented("Not available on iOS")
}
@objc func listChannels(_ call: CAPPluginCall) {
call.unimplemented("Not available on iOS")
}
@objc public func didRegisterForRemoteNotificationsWithDeviceToken(notification: NSNotification) {
appDelegateRegistrationCalled = true
if let deviceToken = notification.object as? Data {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
notifyListeners("registration", data: [
"value": deviceTokenString
])
} else if let stringToken = notification.object as? String {
notifyListeners("registration", data: [
"value": stringToken
])
} else {
notifyListeners("registrationError", data: [
"error": PushNotificationError.tokenParsingFailed.localizedDescription
])
}
}
@objc public func didFailToRegisterForRemoteNotificationsWithError(notification: NSNotification) {
appDelegateRegistrationCalled = true
guard let error = notification.object as? Error else {
return
}
notifyListeners("registrationError", data: [
"error": error.localizedDescription
])
}
@objc func openSettings(_ call: CAPPluginCall) {
var urlString = UIApplication.openSettingsURLString
if #available(iOS 16.0, *) {
urlString = UIApplication.openNotificationSettingsURLString
}
guard let url = URL(string: urlString) else {
call.reject("Can't open settings")
return
}
DispatchQueue.main.async {
UIApplication.shared.open(url, completionHandler: { success in
call.resolve(["success": success])
})
}
}
}