0
# Notifications & UI
1
2
Push notifications, local notifications, dialogs, toast messages, and UI interaction components for user engagement and communication.
3
4
## Capabilities
5
6
### Local Notifications
7
8
Schedule and manage local notifications for reminders, alerts, and app engagement without requiring network connectivity.
9
10
```typescript { .api }
11
/**
12
* Local notification configuration interface
13
*/
14
interface ILocalNotification {
15
/** Unique notification ID */
16
id?: number;
17
/** Notification title */
18
title?: string;
19
/** Notification body text */
20
text?: string;
21
/** Notification badge number (iOS) */
22
badge?: number;
23
/** Sound to play (default, file path, or false for silent) */
24
sound?: string | boolean;
25
/** Custom data payload */
26
data?: any;
27
/** Small icon (Android) */
28
icon?: string;
29
/** Large icon (Android) */
30
smallIcon?: string;
31
/** LED color (Android) */
32
color?: string;
33
/** Vibration pattern */
34
vibrate?: boolean;
35
/** LED enabled (Android) */
36
led?: boolean;
37
/** Schedule time for notification */
38
at?: Date;
39
/** Repeat interval (second, minute, hour, day, week, month, year) */
40
every?: string;
41
/** First notification time for repeating notifications */
42
firstAt?: Date;
43
/** Auto cancel when tapped (Android) */
44
autoCancel?: boolean;
45
/** Ongoing notification (Android) */
46
ongoing?: boolean;
47
/** Group key for grouped notifications (Android) */
48
group?: string;
49
/** Summary for grouped notifications (Android) */
50
groupSummary?: boolean;
51
/** Lock screen visibility (Android) */
52
lockscreen?: boolean;
53
/** Priority level (Android) */
54
priority?: number;
55
/** Silent notification */
56
silent?: boolean;
57
/** Wakeup screen when received */
58
wakeup?: boolean;
59
/** Launch app when tapped */
60
launch?: boolean;
61
/** Actions for interactive notifications */
62
actions?: string[];
63
/** Attachments for rich notifications (iOS) */
64
attachments?: string[];
65
}
66
67
/**
68
* LocalNotifications class for managing local notifications
69
*/
70
class LocalNotifications {
71
/**
72
* Schedule one or more notifications
73
* @param options Notification configuration or array of configurations
74
*/
75
static schedule(options?: ILocalNotification | ILocalNotification[]): void;
76
77
/**
78
* Update existing notification
79
* @param options Updated notification configuration
80
*/
81
static update(options?: ILocalNotification): void;
82
83
/**
84
* Clear notification by ID
85
* @param notificationId Notification ID to clear
86
* @returns Promise resolving to success status
87
*/
88
static clear(notificationId: number): Promise<boolean>;
89
90
/**
91
* Clear all notifications
92
* @returns Promise resolving to success status
93
*/
94
static clearAll(): Promise<boolean>;
95
96
/**
97
* Cancel scheduled notification by ID
98
* @param notificationId Notification ID to cancel
99
* @returns Promise resolving to success status
100
*/
101
static cancel(notificationId: number): Promise<boolean>;
102
103
/**
104
* Cancel all scheduled notifications
105
* @returns Promise resolving to success status
106
*/
107
static cancelAll(): Promise<boolean>;
108
109
/**
110
* Check if notification is present in notification center
111
* @param notificationId Notification ID to check
112
* @returns Promise resolving to presence status
113
*/
114
static isPresent(notificationId: number): Promise<boolean>;
115
116
/**
117
* Check if notification is scheduled
118
* @param notificationId Notification ID to check
119
* @returns Promise resolving to scheduled status
120
*/
121
static isScheduled(notificationId: number): Promise<boolean>;
122
123
/**
124
* Check if notification has been triggered
125
* @param notificationId Notification ID to check
126
* @returns Promise resolving to triggered status
127
*/
128
static isTriggered(notificationId: number): Promise<boolean>;
129
130
/**
131
* Check if app has notification permission
132
* @returns Promise resolving to permission status
133
*/
134
static hasPermission(): Promise<boolean>;
135
136
/**
137
* Register for notification permissions
138
* @returns Promise resolving to permission grant status
139
*/
140
static registerPermission(): Promise<boolean>;
141
142
/**
143
* Listen to notification events
144
* @param eventName Event name (click, trigger, clear, cancel, etc.)
145
* @returns Observable emitting notification events
146
*/
147
static on(eventName: string): Observable<any>;
148
}
149
```
150
151
**Usage Examples:**
152
153
```typescript
154
import { LocalNotifications, ILocalNotification } from 'ionic-native';
155
156
// Request permission and set up notifications
157
async function initializeNotifications() {
158
try {
159
const hasPermission = await LocalNotifications.hasPermission();
160
if (!hasPermission) {
161
const granted = await LocalNotifications.registerPermission();
162
if (!granted) {
163
console.log('Notification permission denied');
164
return;
165
}
166
}
167
168
// Set up event listeners
169
setupNotificationListeners();
170
console.log('Notifications initialized');
171
} catch (error) {
172
console.error('Failed to initialize notifications:', error);
173
}
174
}
175
176
// Set up notification event handlers
177
function setupNotificationListeners() {
178
// Handle notification clicks
179
LocalNotifications.on('click').subscribe((notification) => {
180
console.log('Notification clicked:', notification);
181
handleNotificationClick(notification);
182
});
183
184
// Handle notification triggers
185
LocalNotifications.on('trigger').subscribe((notification) => {
186
console.log('Notification triggered:', notification);
187
});
188
189
// Handle notification clearing
190
LocalNotifications.on('clear').subscribe((notification) => {
191
console.log('Notification cleared:', notification);
192
});
193
194
// Handle notification cancellation
195
LocalNotifications.on('cancel').subscribe((notification) => {
196
console.log('Notification cancelled:', notification);
197
});
198
}
199
200
// Schedule immediate notification
201
function showImmediateNotification(title: string, text: string, data?: any) {
202
const notification: ILocalNotification = {
203
id: Date.now(),
204
title,
205
text,
206
data,
207
sound: true,
208
vibrate: true,
209
led: true,
210
priority: 2,
211
wakeup: true,
212
launch: true
213
};
214
215
LocalNotifications.schedule(notification);
216
}
217
218
// Schedule delayed notification
219
function scheduleDelayedNotification(title: string, text: string, delayMinutes: number) {
220
const scheduleTime = new Date();
221
scheduleTime.setMinutes(scheduleTime.getMinutes() + delayMinutes);
222
223
const notification: ILocalNotification = {
224
id: Date.now(),
225
title,
226
text,
227
at: scheduleTime,
228
sound: 'default',
229
badge: 1,
230
data: {
231
type: 'delayed',
232
scheduledFor: scheduleTime.toISOString()
233
}
234
};
235
236
LocalNotifications.schedule(notification);
237
console.log(`Notification scheduled for ${scheduleTime}`);
238
}
239
240
// Schedule recurring notifications
241
function scheduleRecurringReminder(title: string, text: string, interval: string, startTime?: Date) {
242
const notification: ILocalNotification = {
243
id: Math.floor(Math.random() * 1000000),
244
title,
245
text,
246
every: interval, // 'minute', 'hour', 'day', 'week', 'month', 'year'
247
firstAt: startTime || new Date(),
248
sound: true,
249
badge: 1,
250
data: {
251
type: 'recurring',
252
interval
253
}
254
};
255
256
LocalNotifications.schedule(notification);
257
console.log(`Recurring notification scheduled (${interval})`);
258
}
259
260
// Medication reminder system
261
class MedicationReminder {
262
private reminders: Map<string, number[]> = new Map();
263
264
scheduleReminder(medicationName: string, times: string[], startDate: Date = new Date()) {
265
const notificationIds: number[] = [];
266
267
times.forEach((time, index) => {
268
const [hours, minutes] = time.split(':').map(Number);
269
const scheduleDate = new Date(startDate);
270
scheduleDate.setHours(hours, minutes, 0, 0);
271
272
const notificationId = Date.now() + index;
273
const notification: ILocalNotification = {
274
id: notificationId,
275
title: 'Medication Reminder',
276
text: `Time to take ${medicationName}`,
277
every: 'day',
278
firstAt: scheduleDate,
279
sound: 'default',
280
badge: 1,
281
priority: 2,
282
actions: ['Take', 'Snooze', 'Skip'],
283
data: {
284
type: 'medication',
285
medication: medicationName,
286
time: time
287
}
288
};
289
290
LocalNotifications.schedule(notification);
291
notificationIds.push(notificationId);
292
});
293
294
this.reminders.set(medicationName, notificationIds);
295
console.log(`Scheduled ${times.length} reminders for ${medicationName}`);
296
}
297
298
async cancelReminder(medicationName: string) {
299
const ids = this.reminders.get(medicationName);
300
if (ids) {
301
for (const id of ids) {
302
await LocalNotifications.cancel(id);
303
}
304
this.reminders.delete(medicationName);
305
console.log(`Cancelled reminders for ${medicationName}`);
306
}
307
}
308
309
async listActiveReminders() {
310
const active: { [key: string]: string[] } = {};
311
312
for (const [medication, ids] of this.reminders) {
313
const scheduledTimes: string[] = [];
314
315
for (const id of ids) {
316
const isScheduled = await LocalNotifications.isScheduled(id);
317
if (isScheduled) {
318
// Get notification details if needed
319
scheduledTimes.push(`ID: ${id}`);
320
}
321
}
322
323
if (scheduledTimes.length > 0) {
324
active[medication] = scheduledTimes;
325
}
326
}
327
328
return active;
329
}
330
}
331
```
332
333
### Push Notifications
334
335
Handle remote push notifications from various services with registration, event handling, and badge management.
336
337
```typescript { .api }
338
/**
339
* Push notification registration response
340
*/
341
interface RegistrationEventResponse {
342
/** Registration token/ID for push service */
343
registrationId: string;
344
/** Registration type */
345
registrationType: string;
346
}
347
348
/**
349
* Push notification event response
350
*/
351
interface NotificationEventResponse {
352
/** Notification message */
353
message: string;
354
/** Notification title */
355
title?: string;
356
/** Number of unread notifications */
357
count: string;
358
/** Additional notification data */
359
additionalData: NotificationEventAdditionalData;
360
/** Whether app was in foreground */
361
foreground: boolean;
362
/** Whether notification was cold start */
363
coldstart: boolean;
364
}
365
366
/**
367
* Additional push notification data
368
*/
369
interface NotificationEventAdditionalData {
370
/** Custom payload data */
371
[key: string]: any;
372
/** Whether notification was dismissed */
373
dismissed?: boolean;
374
/** Action identifier (for interactive notifications) */
375
actionCallback?: string;
376
}
377
378
/**
379
* iOS-specific push options
380
*/
381
interface IOSPushOptions {
382
/** Alert notifications enabled */
383
alert?: boolean;
384
/** Badge notifications enabled */
385
badge?: boolean;
386
/** Sound notifications enabled */
387
sound?: boolean;
388
/** Clear badge automatically */
389
clearBadge?: boolean;
390
/** Categories for interactive notifications */
391
categories?: any[];
392
}
393
394
/**
395
* Android-specific push options
396
*/
397
interface AndroidPushOptions {
398
/** Sender ID for GCM/FCM */
399
senderID?: string;
400
/** Default small icon */
401
icon?: string;
402
/** Default icon color */
403
iconColor?: string;
404
/** Default sound */
405
sound?: boolean;
406
/** Default vibration */
407
vibrate?: boolean;
408
/** Clear notifications on app startup */
409
clearNotifications?: boolean;
410
/** Force show even when app is in foreground */
411
forceShow?: boolean;
412
/** Topics to subscribe to */
413
topics?: string[];
414
}
415
416
/**
417
* Cross-platform push options
418
*/
419
interface PushOptions {
420
/** iOS-specific options */
421
ios?: IOSPushOptions;
422
/** Android-specific options */
423
android?: AndroidPushOptions;
424
/** Windows-specific options */
425
windows?: any;
426
/** Browser-specific options */
427
browser?: any;
428
}
429
430
/**
431
* Push notification object for managing push services
432
*/
433
interface PushObject {
434
/**
435
* Add event listener for push events
436
* @param event Event name (registration, notification, error)
437
* @returns Observable emitting push events
438
*/
439
on(event: string): Observable<NotificationEventResponse | RegistrationEventResponse>;
440
441
/**
442
* Unregister from push notifications
443
* @returns Promise indicating unregistration completion
444
*/
445
unregister(): Promise<any>;
446
447
/**
448
* Set application icon badge number (iOS)
449
* @param badgeNumber Badge number to set
450
* @returns Promise indicating badge update completion
451
*/
452
setApplicationIconBadgeNumber(badgeNumber: number): Promise<any>;
453
454
/**
455
* Get current application icon badge number (iOS)
456
* @returns Promise resolving to current badge number
457
*/
458
getApplicationIconBadgeNumber(): Promise<number>;
459
460
/**
461
* Finish handling notification (iOS background processing)
462
*/
463
finish(): void;
464
465
/**
466
* Clear all notifications from notification center
467
* @returns Promise indicating clear completion
468
*/
469
clearAllNotifications(): Promise<any>;
470
}
471
472
/**
473
* Push class for push notification management
474
*/
475
class Push {
476
/**
477
* Initialize push notifications
478
* @param options Push configuration options
479
* @returns PushObject instance
480
*/
481
static init(options: PushOptions): PushObject;
482
483
/**
484
* Check if push notification permission is granted
485
* @returns Promise resolving to permission status
486
*/
487
static hasPermission(): Promise<{ isEnabled: boolean; }>;
488
}
489
```
490
491
**Usage Examples:**
492
493
```typescript
494
import { Push, PushOptions, PushObject } from 'ionic-native';
495
496
// Initialize push notifications
497
function initializePush(): PushObject {
498
const options: PushOptions = {
499
android: {
500
senderID: '123456789',
501
icon: 'phonegap',
502
iconColor: '#0000FF',
503
sound: true,
504
vibrate: true,
505
clearNotifications: true,
506
forceShow: true
507
},
508
ios: {
509
alert: true,
510
badge: true,
511
sound: true,
512
clearBadge: true
513
}
514
};
515
516
const pushObject = Push.init(options);
517
518
// Set up event handlers
519
setupPushHandlers(pushObject);
520
521
return pushObject;
522
}
523
524
// Set up push notification event handlers
525
function setupPushHandlers(pushObject: PushObject) {
526
// Handle successful registration
527
pushObject.on('registration').subscribe((registration) => {
528
console.log('Device registered for push:', registration.registrationId);
529
530
// Send registration token to your server
531
sendTokenToServer(registration.registrationId);
532
});
533
534
// Handle incoming notifications
535
pushObject.on('notification').subscribe((notification) => {
536
console.log('Push notification received:', notification);
537
538
if (notification.additionalData.foreground) {
539
// App is in foreground - show custom UI
540
showInAppNotification(notification);
541
} else {
542
// App was opened from notification
543
handleNotificationOpen(notification);
544
}
545
546
// Finish processing (iOS)
547
pushObject.finish();
548
});
549
550
// Handle registration errors
551
pushObject.on('error').subscribe((error) => {
552
console.error('Push notification error:', error);
553
});
554
}
555
556
// Send registration token to server
557
async function sendTokenToServer(token: string) {
558
try {
559
await fetch('https://api.example.com/register-device', {
560
method: 'POST',
561
headers: {
562
'Content-Type': 'application/json',
563
'Authorization': 'Bearer your-auth-token'
564
},
565
body: JSON.stringify({
566
token,
567
platform: Device.platform,
568
uuid: Device.uuid
569
})
570
});
571
572
console.log('Registration token sent to server');
573
} catch (error) {
574
console.error('Failed to send token to server:', error);
575
}
576
}
577
578
// Handle notification when app is in foreground
579
function showInAppNotification(notification: any) {
580
// Create custom in-app notification UI
581
const notificationElement = document.createElement('div');
582
notificationElement.className = 'in-app-notification';
583
notificationElement.innerHTML = `
584
<div class="notification-content">
585
<h4>${notification.title}</h4>
586
<p>${notification.message}</p>
587
<button onclick="this.parentElement.parentElement.remove()">Close</button>
588
</div>
589
`;
590
591
document.body.appendChild(notificationElement);
592
593
// Auto-remove after 5 seconds
594
setTimeout(() => {
595
if (notificationElement.parentElement) {
596
notificationElement.remove();
597
}
598
}, 5000);
599
}
600
601
// Handle notification tap when app was closed
602
function handleNotificationOpen(notification: any) {
603
console.log('App opened from notification:', notification);
604
605
// Navigate based on notification data
606
if (notification.additionalData.type === 'message') {
607
navigateToMessages(notification.additionalData.messageId);
608
} else if (notification.additionalData.type === 'order') {
609
navigateToOrder(notification.additionalData.orderId);
610
}
611
}
612
613
// Push notification service class
614
class PushNotificationService {
615
private pushObject: PushObject;
616
private registrationToken: string = '';
617
618
async initialize() {
619
// Check permission
620
const permission = await Push.hasPermission();
621
if (!permission.isEnabled) {
622
console.log('Push notifications not enabled');
623
return;
624
}
625
626
this.pushObject = initializePush();
627
}
628
629
async updateBadgeCount(count: number) {
630
if (this.pushObject && Device.platform === 'iOS') {
631
await this.pushObject.setApplicationIconBadgeNumber(count);
632
}
633
}
634
635
async clearBadge() {
636
await this.updateBadgeCount(0);
637
}
638
639
async clearAllNotifications() {
640
if (this.pushObject) {
641
await this.pushObject.clearAllNotifications();
642
}
643
}
644
645
async unregister() {
646
if (this.pushObject) {
647
await this.pushObject.unregister();
648
console.log('Unregistered from push notifications');
649
}
650
}
651
652
getRegistrationToken(): string {
653
return this.registrationToken;
654
}
655
}
656
```
657
658
### OneSignal Integration
659
660
Advanced push notification service with segmentation, A/B testing, and analytics.
661
662
```typescript { .api }
663
/**
664
* OneSignal notification object
665
*/
666
interface OSNotification {
667
/** Notification ID */
668
notificationID?: string;
669
/** Notification content */
670
contents: any;
671
/** Notification heading */
672
headings?: any;
673
/** Whether notification is app in focus */
674
isAppInFocus: boolean;
675
/** Shown notification */
676
shown: boolean;
677
/** Silent notification */
678
silentNotification?: boolean;
679
/** Additional data */
680
additionalData?: any;
681
/** Small icon (Android) */
682
smallIcon?: string;
683
/** Large icon (Android) */
684
largeIcon?: string;
685
/** Big picture (Android) */
686
bigPicture?: string;
687
/** Small icon accent color (Android) */
688
smallIconAccentColor?: string;
689
/** Launch URL */
690
launchURL?: string;
691
/** Sound file */
692
sound?: string;
693
/** LED color (Android) */
694
ledColor?: string;
695
/** Lock screen visibility (Android) */
696
lockScreenVisibility?: number;
697
/** Group key (Android) */
698
groupKey?: string;
699
/** Group message (Android) */
700
groupMessage?: string;
701
/** Action buttons */
702
actionButtons?: any[];
703
/** From projection ID */
704
fromProjectNumber?: string;
705
/** Priority */
706
priority?: number;
707
/** Raw payload */
708
rawPayload?: string;
709
}
710
711
/**
712
* OneSignal notification opened result
713
*/
714
interface OSNotificationOpenedResult {
715
/** Action taken */
716
action: {
717
/** Action type (Opened, ActionTaken) */
718
type: string;
719
/** Action ID (for action buttons) */
720
actionID?: string;
721
};
722
/** Notification object */
723
notification: OSNotification;
724
}
725
726
/**
727
* OneSignal user information
728
*/
729
interface OSUserInfo {
730
/** Player ID */
731
userId: string;
732
/** Push token */
733
pushToken: string;
734
/** Email address */
735
emailAddress?: string;
736
}
737
738
/**
739
* OneSignal class for advanced push notifications
740
*/
741
class OneSignal {
742
/**
743
* Start OneSignal initialization
744
* @param appId OneSignal App ID
745
* @param googleProjectId Google Project ID (Android)
746
* @returns OneSignal initialization object
747
*/
748
static startInit(appId: string, googleProjectId?: string): any;
749
750
/**
751
* Handle notification received events
752
* @returns Observable emitting received notifications
753
*/
754
static handleNotificationReceived(): Observable<OSNotification>;
755
756
/**
757
* Handle notification opened events
758
* @returns Observable emitting notification open events
759
*/
760
static handleNotificationOpened(): Observable<OSNotificationOpenedResult>;
761
762
/**
763
* Complete OneSignal initialization
764
*/
765
static endInit(): void;
766
767
/**
768
* Get user tags
769
* @returns Promise resolving to tags object
770
*/
771
static getTags(): Promise<any>;
772
773
/**
774
* Get user IDs
775
* @returns Promise resolving to user info
776
*/
777
static getIds(): Promise<OSUserInfo>;
778
779
/**
780
* Send tag key-value pair
781
* @param key Tag key
782
* @param value Tag value
783
*/
784
static sendTag(key: string, value: string): void;
785
786
/**
787
* Send multiple tags
788
* @param json Tags object
789
*/
790
static sendTags(json: any): void;
791
792
/**
793
* Delete tag
794
* @param key Tag key to delete
795
*/
796
static deleteTag(key: string): void;
797
798
/**
799
* Delete multiple tags
800
* @param keys Array of tag keys to delete
801
*/
802
static deleteTags(keys: string[]): void;
803
804
/**
805
* Register for push notifications
806
*/
807
static registerForPushNotifications(): void;
808
809
/**
810
* Enable vibration
811
* @param enable Whether to enable vibration
812
*/
813
static enableVibrate(enable: boolean): void;
814
815
/**
816
* Enable sound
817
* @param enable Whether to enable sound
818
*/
819
static enableSound(enable: boolean): void;
820
821
/**
822
* Set subscription status
823
* @param enable Whether user is subscribed
824
*/
825
static setSubscription(enable: boolean): void;
826
827
/**
828
* Post notification to other users
829
* @param notificationObj Notification configuration
830
* @returns Promise resolving to post result
831
*/
832
static postNotification(notificationObj: OSNotification): Promise<any>;
833
834
/**
835
* Sync hashed email for email targeting
836
* @param email User email address
837
*/
838
static syncHashedEmail(email: string): void;
839
840
/**
841
* Prompt for location permission
842
*/
843
static promptLocation(): void;
844
845
/**
846
* Clear all OneSignal notifications
847
*/
848
static clearOneSignalNotifications(): void;
849
850
/**
851
* Set logging level
852
* @param logLevel Log level
853
* @param visualLevel Visual log level
854
*/
855
static setLogLevel(logLevel: any, visualLevel: any): void;
856
}
857
```
858
859
**Usage Examples:**
860
861
```typescript
862
import { OneSignal, OSNotification, OSNotificationOpenedResult } from 'ionic-native';
863
864
// Initialize OneSignal
865
function initializeOneSignal() {
866
OneSignal.startInit('your-app-id', 'your-google-project-id')
867
.handleNotificationReceived()
868
.subscribe((notification: OSNotification) => {
869
console.log('OneSignal notification received:', notification);
870
handleNotificationReceived(notification);
871
});
872
873
OneSignal.startInit('your-app-id', 'your-google-project-id')
874
.handleNotificationOpened()
875
.subscribe((result: OSNotificationOpenedResult) => {
876
console.log('OneSignal notification opened:', result);
877
handleNotificationOpened(result);
878
});
879
880
OneSignal.endInit();
881
882
// Configure settings
883
OneSignal.enableVibrate(true);
884
OneSignal.enableSound(true);
885
OneSignal.registerForPushNotifications();
886
}
887
888
// Handle received notification
889
function handleNotificationReceived(notification: OSNotification) {
890
if (notification.isAppInFocus) {
891
// Show custom in-app notification
892
showCustomNotification(notification);
893
}
894
895
// Update badge or UI based on notification
896
updateAppState(notification.additionalData);
897
}
898
899
// Handle notification opened
900
function handleNotificationOpened(result: OSNotificationOpenedResult) {
901
const { action, notification } = result;
902
903
if (action.type === 'ActionTaken') {
904
// Handle action button press
905
handleNotificationAction(action.actionID, notification);
906
} else {
907
// Handle notification tap
908
navigateFromNotification(notification.additionalData);
909
}
910
}
911
912
// User segmentation and targeting
913
class OneSignalService {
914
async setupUserProfile(userId: string, userProfile: any) {
915
// Set user tags for segmentation
916
const tags = {
917
user_id: userId,
918
user_type: userProfile.type,
919
subscription_tier: userProfile.subscriptionTier,
920
last_active: new Date().toISOString(),
921
preferred_language: userProfile.language || 'en',
922
age_group: this.getAgeGroup(userProfile.age),
923
interests: userProfile.interests?.join(',') || ''
924
};
925
926
OneSignal.sendTags(tags);
927
928
if (userProfile.email) {
929
OneSignal.syncHashedEmail(userProfile.email);
930
}
931
932
console.log('OneSignal user profile configured');
933
}
934
935
async sendNotificationToUser(targetUserId: string, message: string, data?: any) {
936
const notification = {
937
contents: { en: message },
938
include_external_user_ids: [targetUserId],
939
data: data || {}
940
};
941
942
try {
943
const result = await OneSignal.postNotification(notification);
944
console.log('Notification sent successfully:', result);
945
return result;
946
} catch (error) {
947
console.error('Failed to send notification:', error);
948
throw error;
949
}
950
}
951
952
async sendToSegment(segment: string, title: string, message: string, data?: any) {
953
const notification = {
954
headings: { en: title },
955
contents: { en: message },
956
filters: [
957
{ field: 'tag', key: 'user_type', relation: '=', value: segment }
958
],
959
data: data || {}
960
};
961
962
try {
963
const result = await OneSignal.postNotification(notification);
964
console.log('Segment notification sent:', result);
965
return result;
966
} catch (error) {
967
console.error('Failed to send segment notification:', error);
968
throw error;
969
}
970
}
971
972
updateUserActivity() {
973
OneSignal.sendTag('last_active', new Date().toISOString());
974
}
975
976
setUserPreferences(preferences: any) {
977
const tags: any = {};
978
979
if (preferences.notifications !== undefined) {
980
OneSignal.setSubscription(preferences.notifications);
981
}
982
983
if (preferences.sound !== undefined) {
984
OneSignal.enableSound(preferences.sound);
985
tags.sound_enabled = preferences.sound.toString();
986
}
987
988
if (preferences.vibrate !== undefined) {
989
OneSignal.enableVibrate(preferences.vibrate);
990
tags.vibrate_enabled = preferences.vibrate.toString();
991
}
992
993
if (Object.keys(tags).length > 0) {
994
OneSignal.sendTags(tags);
995
}
996
}
997
998
private getAgeGroup(age: number): string {
999
if (age < 18) return 'under_18';
1000
if (age < 25) return '18_24';
1001
if (age < 35) return '25_34';
1002
if (age < 45) return '35_44';
1003
if (age < 55) return '45_54';
1004
return '55_plus';
1005
}
1006
1007
async getUserInfo() {
1008
try {
1009
const [userInfo, tags] = await Promise.all([
1010
OneSignal.getIds(),
1011
OneSignal.getTags()
1012
]);
1013
1014
return { userInfo, tags };
1015
} catch (error) {
1016
console.error('Failed to get user info:', error);
1017
return null;
1018
}
1019
}
1020
}
1021
```
1022
1023
### Toast Messages
1024
1025
Simple, non-intrusive messages that appear briefly at the bottom or top of the screen.
1026
1027
```typescript { .api }
1028
/**
1029
* Toast class for showing brief messages
1030
*/
1031
class Toast {
1032
/**
1033
* Show toast message with custom configuration
1034
* @param message Message to display
1035
* @param duration Duration ('short' or 'long')
1036
* @param position Position ('top', 'center', or 'bottom')
1037
* @returns Promise indicating toast completion
1038
*/
1039
static show(message: string, duration: string, position: string): Promise<any>;
1040
1041
/**
1042
* Show short toast at top of screen
1043
* @param message Message to display
1044
* @returns Promise indicating toast completion
1045
*/
1046
static showShortTop(message: string): Promise<any>;
1047
1048
/**
1049
* Show short toast at center of screen
1050
* @param message Message to display
1051
* @returns Promise indicating toast completion
1052
*/
1053
static showShortCenter(message: string): Promise<any>;
1054
1055
/**
1056
* Show short toast at bottom of screen
1057
* @param message Message to display
1058
* @returns Promise indicating toast completion
1059
*/
1060
static showShortBottom(message: string): Promise<any>;
1061
1062
/**
1063
* Show long toast at top of screen
1064
* @param message Message to display
1065
* @returns Promise indicating toast completion
1066
*/
1067
static showLongTop(message: string): Promise<any>;
1068
1069
/**
1070
* Show long toast at center of screen
1071
* @param message Message to display
1072
* @returns Promise indicating toast completion
1073
*/
1074
static showLongCenter(message: string): Promise<any>;
1075
1076
/**
1077
* Show long toast at bottom of screen
1078
* @param message Message to display
1079
* @returns Promise indicating toast completion
1080
*/
1081
static showLongBottom(message: string): Promise<any>;
1082
}
1083
```
1084
1085
### Dialogs
1086
1087
Native dialog boxes for alerts, confirmations, prompts, and custom interactions.
1088
1089
```typescript { .api }
1090
/**
1091
* Dialog prompt result
1092
*/
1093
interface DialogPromptResult {
1094
/** Button index pressed (1-based) */
1095
buttonIndex: number;
1096
/** Text input value (for prompt dialogs) */
1097
input1?: string;
1098
}
1099
1100
/**
1101
* Dialogs class for native dialog boxes
1102
*/
1103
class Dialogs {
1104
/**
1105
* Show alert dialog
1106
* @param message Alert message
1107
* @param title Dialog title (optional)
1108
* @param buttonName Button text (default: 'OK')
1109
* @returns Promise indicating dialog completion
1110
*/
1111
static alert(message: string, title?: string, buttonName?: string): Promise<any>;
1112
1113
/**
1114
* Show confirmation dialog
1115
* @param message Confirmation message
1116
* @param title Dialog title (optional)
1117
* @param buttonLabels Array of button labels (default: ['OK', 'Cancel'])
1118
* @returns Promise resolving to button index (1-based)
1119
*/
1120
static confirm(message: string, title?: string, buttonLabels?: Array<string>): Promise<number>;
1121
1122
/**
1123
* Show prompt dialog
1124
* @param message Prompt message (optional)
1125
* @param title Dialog title (optional)
1126
* @param buttonLabels Array of button labels (optional)
1127
* @param defaultText Default input text (optional)
1128
* @returns Promise resolving to DialogPromptResult
1129
*/
1130
static prompt(message?: string, title?: string, buttonLabels?: Array<string>, defaultText?: string): Promise<DialogPromptResult>;
1131
1132
/**
1133
* Play device beep sound
1134
* @param times Number of beeps
1135
*/
1136
static beep(times: number): void;
1137
}
1138
```
1139
1140
**Usage Examples:**
1141
1142
```typescript
1143
import { Toast, Dialogs } from 'ionic-native';
1144
1145
// Toast message examples
1146
function showSuccessToast(message: string) {
1147
Toast.showShortBottom(`✓ ${message}`);
1148
}
1149
1150
function showErrorToast(error: string) {
1151
Toast.showLongTop(`✗ ${error}`);
1152
}
1153
1154
function showInfoToast(info: string) {
1155
Toast.showShortCenter(info);
1156
}
1157
1158
// Dialog examples
1159
async function confirmAction(message: string, actionName: string = 'Continue') {
1160
try {
1161
const buttonIndex = await Dialogs.confirm(
1162
message,
1163
'Confirm Action',
1164
[actionName, 'Cancel']
1165
);
1166
1167
return buttonIndex === 1; // First button (actionName) was pressed
1168
} catch (error) {
1169
console.error('Dialog error:', error);
1170
return false;
1171
}
1172
}
1173
1174
async function showUserAlert(title: string, message: string) {
1175
try {
1176
await Dialogs.alert(message, title, 'OK');
1177
} catch (error) {
1178
console.error('Alert error:', error);
1179
}
1180
}
1181
1182
async function getUserInput(title: string, message: string, defaultValue: string = '') {
1183
try {
1184
const result = await Dialogs.prompt(
1185
message,
1186
title,
1187
['Save', 'Cancel'],
1188
defaultValue
1189
);
1190
1191
if (result.buttonIndex === 1) {
1192
return result.input1;
1193
}
1194
1195
return null;
1196
} catch (error) {
1197
console.error('Prompt error:', error);
1198
return null;
1199
}
1200
}
1201
1202
// Notification feedback manager
1203
class NotificationFeedback {
1204
static showSuccess(message: string) {
1205
Toast.showShortBottom(`✓ ${message}`);
1206
}
1207
1208
static showError(message: string) {
1209
Toast.showLongTop(`✗ ${message}`);
1210
Dialogs.beep(1);
1211
}
1212
1213
static showWarning(message: string) {
1214
Toast.show(`⚠ ${message}`, 'long', 'center');
1215
}
1216
1217
static showInfo(message: string) {
1218
Toast.showShortCenter(`ℹ ${message}`);
1219
}
1220
1221
static async confirmDelete(itemName: string) {
1222
return await confirmAction(
1223
`Are you sure you want to delete "${itemName}"? This action cannot be undone.`,
1224
'Delete'
1225
);
1226
}
1227
1228
static async confirmLogout() {
1229
return await confirmAction(
1230
'Are you sure you want to log out?',
1231
'Log Out'
1232
);
1233
}
1234
1235
static async getTextInput(title: string, placeholder: string = '') {
1236
return await getUserInput(title, 'Please enter the text:', placeholder);
1237
}
1238
1239
static async getPasswordInput(title: string = 'Enter Password') {
1240
return await getUserInput(title, 'Please enter your password:');
1241
}
1242
}
1243
1244
// Advanced dialog patterns
1245
class DialogService {
1246
static async showDeleteConfirmation(itemType: string, itemName: string) {
1247
const message = `This will permanently delete the ${itemType} "${itemName}". Are you sure?`;
1248
1249
const buttonIndex = await Dialogs.confirm(
1250
message,
1251
'Delete Confirmation',
1252
['Delete', 'Keep', 'Cancel']
1253
);
1254
1255
switch (buttonIndex) {
1256
case 1: return 'delete';
1257
case 2: return 'keep';
1258
default: return 'cancel';
1259
}
1260
}
1261
1262
static async showSaveChangesDialog() {
1263
const buttonIndex = await Dialogs.confirm(
1264
'You have unsaved changes. What would you like to do?',
1265
'Unsaved Changes',
1266
['Save', 'Discard', 'Cancel']
1267
);
1268
1269
switch (buttonIndex) {
1270
case 1: return 'save';
1271
case 2: return 'discard';
1272
default: return 'cancel';
1273
}
1274
}
1275
1276
static async getRatingInput() {
1277
const result = await Dialogs.prompt(
1278
'Please rate this item from 1 to 5:',
1279
'Rating',
1280
['Submit', 'Cancel'],
1281
'5'
1282
);
1283
1284
if (result.buttonIndex === 1) {
1285
const rating = parseInt(result.input1 || '0');
1286
if (rating >= 1 && rating <= 5) {
1287
return rating;
1288
} else {
1289
await Dialogs.alert('Please enter a rating between 1 and 5.', 'Invalid Rating');
1290
return null;
1291
}
1292
}
1293
1294
return null;
1295
}
1296
1297
static playNotificationSound(urgency: 'low' | 'medium' | 'high') {
1298
const beepCounts = { low: 1, medium: 2, high: 3 };
1299
Dialogs.beep(beepCounts[urgency]);
1300
}
1301
}
1302
```