forked from NativeScript/firebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ios.ts
345 lines (304 loc) · 9.44 KB
/
index.ios.ts
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { Application, ApplicationSettings, Device } from '@nativescript/core';
import { IMessagingCore, Permissions } from '.';
import { AuthorizationStatus } from './common';
declare const TNSFirebaseCore;
let _registerDeviceForRemoteMessages = {
resolve: null,
reject: null,
};
const REMOTE_NOTIFICATIONS_REGISTRATION_STATUS = 'org.nativescript.firebase.notifications.status';
let defaultInstance: MessagingCore;
const onMessageCallbacks: Set<(message: any) => void> = new Set();
const onTokenCallbacks: Set<(token: any) => void> = new Set();
const onNotificationTapCallbacks: Set<(message: any) => void> = new Set();
function deserialize(data: any): any {
if (data instanceof NSNull) {
return null;
}
if (data instanceof NSArray) {
let array = [];
for (let i = 0, n = data.count; i < n; i++) {
array[i] = deserialize(data.objectAtIndex(i));
}
return array;
}
if (data instanceof NSDictionary) {
let dict = {};
for (let i = 0, n = data.allKeys.count; i < n; i++) {
let key = data.allKeys.objectAtIndex(i);
dict[key] = deserialize(data.objectForKey(key));
}
return dict;
}
return data;
}
export class MessagingCore implements IMessagingCore {
_APNSToken;
_onMessage(message: any) {
console.log('_onMessage', message);
if (onMessageCallbacks.size > 0) {
const msg = deserialize(message);
onMessageCallbacks.forEach((cb) => {
cb(msg);
});
} else {
MessagingCore._messageQueues._onMessage.push(message);
}
}
_onToken(token: string) {
this._APNSToken = token;
console.log('_onToken', token);
if (onTokenCallbacks.size > 0) {
onTokenCallbacks.forEach((cb) => {
cb(token);
});
} else {
MessagingCore._messageQueues._onToken.push(token);
}
}
_onNotificationTap(message: any) {
console.log('_onNotificationTap', message);
if (onNotificationTapCallbacks.size > 0) {
const msg = deserialize(message);
onNotificationTapCallbacks.forEach((cb) => {
cb(msg);
});
} else {
MessagingCore._messageQueues._onNotificationTap.push(message);
}
}
static _onResumeQueue = [];
static _messageQueues = {
_onMessage: [],
_onNotificationTap: [],
_onToken: [],
};
static addToResumeQueue(callback: () => void) {
if (typeof callback !== 'function') {
return;
}
MessagingCore._onResumeQueue.push(callback);
}
static _inForeground = false;
static _appDidLaunch = false;
static get inForeground() {
return MessagingCore._inForeground;
}
static get appDidLaunch() {
return MessagingCore._appDidLaunch;
}
constructor() {
if (defaultInstance) {
return defaultInstance;
}
defaultInstance = this;
Application.on('launch', (args) => {
MessagingCore._onResumeQueue.forEach((callback) => {
callback();
});
MessagingCore._onResumeQueue.splice(0);
});
Application.on('resume', (args) => {
MessagingCore._inForeground = true;
MessagingCore._appDidLaunch = true;
});
Application.on('suspend', (args) => {
MessagingCore._inForeground = false;
});
NSCFirebaseMessagingCore.onMessageCallback = this._onMessage.bind(this);
NSCFirebaseMessagingCore.onTokenCallback = this._onToken.bind(this);
NSCFirebaseMessagingCore.onNotificationTapCallback = this._onNotificationTap.bind(this);
}
static getInstance() {
if (defaultInstance) {
return defaultInstance;
}
return new MessagingCore();
}
get showNotificationsWhenInForeground(): boolean {
return NSCFirebaseMessagingCore.showNotificationsWhenInForeground;
}
set showNotificationsWhenInForeground(value: boolean) {
NSCFirebaseMessagingCore.showNotificationsWhenInForeground = value;
}
getCurrentToken(): Promise<string> {
return new Promise((resolve, reject) => {
if (!TNSFirebaseCore.isSimulator() && !UIApplication.sharedApplication.registeredForRemoteNotifications) {
reject(new Error('You must be registered for remote messages before calling getToken, see MessagingCore.getInstance().registerDeviceForRemoteMessages()'));
return;
}
if (!this._APNSToken) {
reject(new Error('No token found'));
return;
}
resolve(this.getAPNSToken());
});
}
getAPNSToken() {
return this._APNSToken;
}
_hasPermission(resolve, reject) {
if (parseInt(Device.osVersion) >= 10) {
UNUserNotificationCenter.currentNotificationCenter().getNotificationSettingsWithCompletionHandler((settings) => {
let status = AuthorizationStatus.NOT_DETERMINED;
switch (settings.authorizationStatus) {
case UNAuthorizationStatus.Authorized:
status = AuthorizationStatus.AUTHORIZED;
break;
case UNAuthorizationStatus.Denied:
status = AuthorizationStatus.DENIED;
break;
case UNAuthorizationStatus.Ephemeral:
status = AuthorizationStatus.EPHEMERAL;
break;
case UNAuthorizationStatus.Provisional:
status = AuthorizationStatus.PROVISIONAL;
break;
case UNAuthorizationStatus.NotDetermined:
status = AuthorizationStatus.NOT_DETERMINED;
break;
}
resolve(status);
});
} else {
resolve(AuthorizationStatus.AUTHORIZED);
}
}
hasPermission(): Promise<AuthorizationStatus> {
return new Promise((resolve, reject) => {
this._hasPermission(resolve, reject);
});
}
addOnMessage(listener: (message: any) => any) {
if (typeof listener === 'function') {
onMessageCallbacks.add(listener);
this._triggerPendingCallbacks('_onMessage');
}
}
removeOnMessage(listener: (message: any) => any): boolean {
if (typeof listener === 'function') {
return onMessageCallbacks.delete(listener);
}
return false;
}
addOnToken(listener: (token: string) => any) {
if (typeof listener === 'function') {
onTokenCallbacks.add(listener);
this._triggerPendingCallbacks('_onToken');
}
}
removeOnToken(listener: (token: string) => any): boolean {
if (typeof listener === 'function') {
return onTokenCallbacks.delete(listener);
}
return false;
}
addOnNotificationTap(listener: (message: any) => any) {
if (typeof listener === 'function') {
onNotificationTapCallbacks.add(listener);
this._triggerPendingCallbacks('_onNotificationTap');
}
}
removeOnNotificationTap(listener: (message: any) => any): boolean {
if (typeof listener === 'function') {
return onNotificationTapCallbacks.delete(listener);
}
return false;
}
registerDeviceForRemoteMessages(): Promise<void> {
return new Promise((resolve, reject) => {
if (TNSFirebaseCore.isSimulator()) {
ApplicationSettings.setBoolean(REMOTE_NOTIFICATIONS_REGISTRATION_STATUS, true);
resolve();
}
NSCFirebaseMessagingCore.registerDeviceForRemoteMessagesCallback = (result, error) => {
if (error) {
const err: any = new Error(error?.localizedDescription);
err.native = error;
reject(err);
} else {
resolve();
}
};
if (UIApplication?.sharedApplication) {
UIApplication?.sharedApplication?.registerForRemoteNotifications?.();
} else {
const cb = (args) => {
UIApplication?.sharedApplication?.registerForRemoteNotifications?.();
Application.off('launch', cb);
};
Application.on('launch', cb);
}
});
}
requestPermission(permissions?: Permissions): Promise<AuthorizationStatus> {
return new Promise((resolve, reject) => {
const version = parseInt(Device.osVersion);
if (version >= 10) {
let options = UNAuthorizationOptionNone;
if (permissions?.ios?.alert ?? true) {
options = options | UNAuthorizationOptions.Alert;
}
if (permissions?.ios?.badge ?? true) {
options = options | UNAuthorizationOptions.Badge;
}
if (permissions?.ios?.sound ?? true) {
options = options | UNAuthorizationOptions.Sound;
}
if (permissions?.ios?.carPlay ?? true) {
options = options | UNAuthorizationOptions.CarPlay;
}
if (version >= 12) {
if (permissions?.ios?.criticalAlert) {
options = options | UNAuthorizationOptions.CriticalAlert;
}
if (permissions?.ios?.provisional) {
options = options | UNAuthorizationOptions.Provisional;
}
}
if (version >= 13 && version <= 15) {
options = options | UNAuthorizationOptions.Announcement;
}
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptionsCompletionHandler(options, (result, error) => {
if (error) {
const err: any = new Error(error?.localizedDescription);
err.native = error;
reject(err);
reject(err);
} else {
this._hasPermission(resolve, reject);
}
});
} else {
const notificationTypes = UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge;
const settings = UIUserNotificationSettings.settingsForTypesCategories(notificationTypes, null);
UIApplication.sharedApplication.registerUserNotificationSettings(settings);
this._hasPermission(resolve, reject);
}
});
}
unregisterDeviceForRemoteMessages(): Promise<void> {
return new Promise((resolve, reject) => {
try {
UIApplication.sharedApplication.unregisterForRemoteNotifications();
ApplicationSettings.setBoolean(REMOTE_NOTIFICATIONS_REGISTRATION_STATUS, false);
resolve();
} catch (e) {
reject(e);
}
});
}
get isDeviceRegisteredForRemoteMessages(): boolean {
return UIApplication.sharedApplication.registeredForRemoteNotifications;
}
private _triggerPendingCallbacks(type: keyof typeof MessagingCore._messageQueues) {
const queue = MessagingCore._messageQueues[type];
if (queue.length > 0) {
MessagingCore._messageQueues[type] = [];
queue.forEach((message) => {
this[type](message);
});
}
}
}
export { AuthorizationStatus } from './common';