-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathFlutterApnsPlugin.swift
284 lines (238 loc) · 10.7 KB
/
FlutterApnsPlugin.swift
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import Flutter
import UserNotifications
func getFlutterError(_ error: Error) -> FlutterError {
let e = error as NSError
return FlutterError(code: "Error: \(e.code)", message: e.domain, details: error.localizedDescription)
}
@objc public class FlutterApnsPlugin: NSObject, FlutterPlugin, UNUserNotificationCenterDelegate {
internal init(channel: FlutterMethodChannel) {
self.channel = channel
}
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_apns", binaryMessenger: registrar.messenger())
let instance = FlutterApnsPlugin(channel: channel)
registrar.addApplicationDelegate(instance)
registrar.addMethodCallDelegate(instance, channel: channel)
}
let channel: FlutterMethodChannel
var launchNotification: [String: Any]?
var resumingFromBackground = false
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "requestNotificationPermissions":
requestNotificationPermissions(call, result: result)
case "configure":
assert(
UNUserNotificationCenter.current().delegate != nil,
"UNUserNotificationCenter.current().delegate is not set. Check readme at https://pub.dev/packages/flutter_apns."
)
UIApplication.shared.registerForRemoteNotifications()
// check for onLaunch notification *after* configure has been ran
if let launchNotification = launchNotification {
channel.invokeMethod("onLaunch", arguments: launchNotification)
self.launchNotification = nil
return
}
result(nil)
case "getAuthorizationStatus":
getAuthorizationStatus(result)
case "unregister":
UIApplication.shared.unregisterForRemoteNotifications()
result(nil)
case "setNotificationCategories":
setNotificationCategories(arguments: call.arguments!)
result(nil)
default:
assertionFailure(call.method)
result(FlutterMethodNotImplemented)
}
}
func setNotificationCategories(arguments: Any) {
let arguments = arguments as! [[String: Any]]
func decodeCategory(map: [String: Any]) -> UNNotificationCategory {
return UNNotificationCategory(
identifier: map["identifier"] as! String,
actions: (map["actions"] as! [[String: Any]]).map(decodeAction),
intentIdentifiers: map["intentIdentifiers"] as! [String],
options: decodeCategoryOptions(data: map["options"] as! [String])
)
}
func decodeCategoryOptions(data: [String]) -> UNNotificationCategoryOptions {
let mapped = data.compactMap {
UNNotificationCategoryOptions.stringToValue[$0]
}
return .init(mapped)
}
func decodeAction(map: [String: Any]) -> UNNotificationAction {
return UNNotificationAction(
identifier: map["identifier"] as! String,
title: map["title"] as! String,
options: decodeActionOptions(data: map["options"] as! [String])
)
}
func decodeActionOptions(data: [String]) -> UNNotificationActionOptions {
let mapped = data.compactMap {
UNNotificationActionOptions.stringToValue[$0]
}
return .init(mapped)
}
let categories = arguments.map(decodeCategory)
UNUserNotificationCenter.current().setNotificationCategories(Set(categories))
}
func getAuthorizationStatus(_ result: @escaping FlutterResult) {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
switch settings.authorizationStatus {
case .authorized:
result("authorized")
case .denied:
result("denied")
case .notDetermined:
result("notDetermined")
default:
result("unsupported")
}
}
}
func requestNotificationPermissions(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let center = UNUserNotificationCenter.current()
let application = UIApplication.shared
func readBool(_ key: String) -> Bool {
(call.arguments as? [String: Any])?[key] as? Bool ?? false
}
assert(center.delegate != nil)
var options = [UNAuthorizationOptions]()
if readBool("sound") {
options.append(.sound)
}
if readBool("badge") {
options.append(.badge)
}
if readBool("alert") {
options.append(.alert)
}
var provisionalRequested = false
if #available(iOS 12.0, *) {
if readBool("criticalAlert") {
options.append(.criticalAlert)
}
if readBool("provisional") {
options.append(.provisional)
provisionalRequested = true
}
}
let optionsUnion = UNAuthorizationOptions(options)
center.requestAuthorization(options: optionsUnion) { (granted, error) in
if let error = error {
result(getFlutterError(error))
return
}
center.getNotificationSettings { (settings) in
var map = [
"sound": settings.soundSetting == .enabled,
"badge": settings.badgeSetting == .enabled,
"alert": settings.alertSetting == .enabled,
"provisional": granted && provisionalRequested
]
if #available(iOS 12.0, *) {
map["criticalAlert"] = settings.criticalAlertSetting == .enabled
}
self.channel.invokeMethod("onIosSettingsRegistered", arguments: map)
}
result(granted)
}
application.registerForRemoteNotifications()
}
//MARK: - AppDelegate
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [AnyHashable : Any] = [:]) -> Bool {
if let launchNotification = launchOptions[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: Any] {
self.launchNotification = FlutterApnsSerialization.remoteMessageUserInfo(toDict: launchNotification)
}
return true
}
public func applicationDidEnterBackground(_ application: UIApplication) {
resumingFromBackground = true
}
public func applicationDidBecomeActive(_ application: UIApplication) {
resumingFromBackground = false
UIApplication.shared.applicationIconBadgeNumber = -1;
}
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
channel.invokeMethod("onToken", arguments: deviceToken.hexString)
}
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool {
let userInfo = FlutterApnsSerialization.remoteMessageUserInfo(toDict: userInfo)
if resumingFromBackground {
onResume(userInfo: userInfo)
} else {
channel.invokeMethod("onMessage", arguments: userInfo)
}
completionHandler(.noData)
return true
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
guard userInfo["aps"] != nil else {
return
}
let dict = FlutterApnsSerialization.remoteMessageUserInfo(toDict: userInfo)
channel.invokeMethod("willPresent", arguments: dict) { (result) in
let shouldShow = (result as? Bool) ?? false
if shouldShow {
completionHandler([.alert, .sound])
} else {
completionHandler([])
let userInfo = FlutterApnsSerialization.remoteMessageUserInfo(toDict: userInfo)
self.channel.invokeMethod("onMessage", arguments: userInfo)
}
}
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
var userInfo = response.notification.request.content.userInfo
guard userInfo["aps"] != nil else {
return
}
userInfo["actionIdentifier"] = response.actionIdentifier
let dict = FlutterApnsSerialization.remoteMessageUserInfo(toDict: userInfo)
if launchNotification != nil {
launchNotification = dict
return
}
onResume(userInfo: dict)
completionHandler()
}
func onResume(userInfo: [AnyHashable: Any]) {
channel.invokeMethod("onResume", arguments: userInfo)
}
}
extension UNNotificationCategoryOptions {
static let stringToValue: [String: UNNotificationCategoryOptions] = {
var r: [String: UNNotificationCategoryOptions] = [:]
r["UNNotificationCategoryOptions.customDismissAction"] = .customDismissAction
r["UNNotificationCategoryOptions.allowInCarPlay"] = .allowInCarPlay
if #available(iOS 11.0, *) {
r["UNNotificationCategoryOptions.hiddenPreviewsShowTitle"] = .hiddenPreviewsShowTitle
}
if #available(iOS 11.0, *) {
r["UNNotificationCategoryOptions.hiddenPreviewsShowSubtitle"] = .hiddenPreviewsShowSubtitle
}
if #available(iOS 13.0, *) {
r["UNNotificationCategoryOptions.allowAnnouncement"] = .allowAnnouncement
}
return r
}()
}
extension UNNotificationActionOptions {
static let stringToValue: [String: UNNotificationActionOptions] = {
var r: [String: UNNotificationActionOptions] = [:]
r["UNNotificationActionOptions.authenticationRequired"] = .authenticationRequired
r["UNNotificationActionOptions.destructive"] = .destructive
r["UNNotificationActionOptions.foreground"] = .foreground
return r
}()
}
extension Data {
var hexString: String {
let hexString = map { String(format: "%02.2hhx", $0) }.joined()
return hexString
}
}