CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ionic-native

Native plugin wrappers for Cordova and Ionic with TypeScript, ES6+, Promise and Observable support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

notifications-ui.mddocs/

Notifications & UI

Push notifications, local notifications, dialogs, toast messages, and UI interaction components for user engagement and communication.

Capabilities

Local Notifications

Schedule and manage local notifications for reminders, alerts, and app engagement without requiring network connectivity.

/**
 * Local notification configuration interface
 */
interface ILocalNotification {
  /** Unique notification ID */
  id?: number;
  /** Notification title */
  title?: string;
  /** Notification body text */
  text?: string;
  /** Notification badge number (iOS) */
  badge?: number;
  /** Sound to play (default, file path, or false for silent) */
  sound?: string | boolean;
  /** Custom data payload */
  data?: any;
  /** Small icon (Android) */
  icon?: string;
  /** Large icon (Android) */
  smallIcon?: string;
  /** LED color (Android) */
  color?: string;
  /** Vibration pattern */
  vibrate?: boolean;
  /** LED enabled (Android) */
  led?: boolean;
  /** Schedule time for notification */
  at?: Date;
  /** Repeat interval (second, minute, hour, day, week, month, year) */
  every?: string;
  /** First notification time for repeating notifications */
  firstAt?: Date;
  /** Auto cancel when tapped (Android) */
  autoCancel?: boolean;
  /** Ongoing notification (Android) */
  ongoing?: boolean;
  /** Group key for grouped notifications (Android) */
  group?: string;
  /** Summary for grouped notifications (Android) */
  groupSummary?: boolean;
  /** Lock screen visibility (Android) */
  lockscreen?: boolean;
  /** Priority level (Android) */
  priority?: number;
  /** Silent notification */
  silent?: boolean;
  /** Wakeup screen when received */
  wakeup?: boolean;
  /** Launch app when tapped */
  launch?: boolean;
  /** Actions for interactive notifications */
  actions?: string[];
  /** Attachments for rich notifications (iOS) */
  attachments?: string[];
}

/**
 * LocalNotifications class for managing local notifications
 */
class LocalNotifications {
  /**
   * Schedule one or more notifications
   * @param options Notification configuration or array of configurations
   */
  static schedule(options?: ILocalNotification | ILocalNotification[]): void;

  /**
   * Update existing notification
   * @param options Updated notification configuration
   */
  static update(options?: ILocalNotification): void;

  /**
   * Clear notification by ID
   * @param notificationId Notification ID to clear
   * @returns Promise resolving to success status
   */
  static clear(notificationId: number): Promise<boolean>;

  /**
   * Clear all notifications
   * @returns Promise resolving to success status
   */
  static clearAll(): Promise<boolean>;

  /**
   * Cancel scheduled notification by ID
   * @param notificationId Notification ID to cancel
   * @returns Promise resolving to success status
   */
  static cancel(notificationId: number): Promise<boolean>;

  /**
   * Cancel all scheduled notifications
   * @returns Promise resolving to success status
   */
  static cancelAll(): Promise<boolean>;

  /**
   * Check if notification is present in notification center
   * @param notificationId Notification ID to check
   * @returns Promise resolving to presence status
   */
  static isPresent(notificationId: number): Promise<boolean>;

  /**
   * Check if notification is scheduled
   * @param notificationId Notification ID to check
   * @returns Promise resolving to scheduled status
   */
  static isScheduled(notificationId: number): Promise<boolean>;

  /**
   * Check if notification has been triggered
   * @param notificationId Notification ID to check
   * @returns Promise resolving to triggered status
   */
  static isTriggered(notificationId: number): Promise<boolean>;

  /**
   * Check if app has notification permission
   * @returns Promise resolving to permission status
   */
  static hasPermission(): Promise<boolean>;

  /**
   * Register for notification permissions
   * @returns Promise resolving to permission grant status
   */
  static registerPermission(): Promise<boolean>;

  /**
   * Listen to notification events
   * @param eventName Event name (click, trigger, clear, cancel, etc.)
   * @returns Observable emitting notification events
   */
  static on(eventName: string): Observable<any>;
}

Usage Examples:

import { LocalNotifications, ILocalNotification } from 'ionic-native';

// Request permission and set up notifications
async function initializeNotifications() {
  try {
    const hasPermission = await LocalNotifications.hasPermission();
    if (!hasPermission) {
      const granted = await LocalNotifications.registerPermission();
      if (!granted) {
        console.log('Notification permission denied');
        return;
      }
    }

    // Set up event listeners
    setupNotificationListeners();
    console.log('Notifications initialized');
  } catch (error) {
    console.error('Failed to initialize notifications:', error);
  }
}

// Set up notification event handlers
function setupNotificationListeners() {
  // Handle notification clicks
  LocalNotifications.on('click').subscribe((notification) => {
    console.log('Notification clicked:', notification);
    handleNotificationClick(notification);
  });

  // Handle notification triggers
  LocalNotifications.on('trigger').subscribe((notification) => {
    console.log('Notification triggered:', notification);
  });

  // Handle notification clearing
  LocalNotifications.on('clear').subscribe((notification) => {
    console.log('Notification cleared:', notification);
  });

  // Handle notification cancellation
  LocalNotifications.on('cancel').subscribe((notification) => {
    console.log('Notification cancelled:', notification);
  });
}

// Schedule immediate notification
function showImmediateNotification(title: string, text: string, data?: any) {
  const notification: ILocalNotification = {
    id: Date.now(),
    title,
    text,
    data,
    sound: true,
    vibrate: true,
    led: true,
    priority: 2,
    wakeup: true,
    launch: true
  };

  LocalNotifications.schedule(notification);
}

// Schedule delayed notification
function scheduleDelayedNotification(title: string, text: string, delayMinutes: number) {
  const scheduleTime = new Date();
  scheduleTime.setMinutes(scheduleTime.getMinutes() + delayMinutes);

  const notification: ILocalNotification = {
    id: Date.now(),
    title,
    text,
    at: scheduleTime,
    sound: 'default',
    badge: 1,
    data: {
      type: 'delayed',
      scheduledFor: scheduleTime.toISOString()
    }
  };

  LocalNotifications.schedule(notification);
  console.log(`Notification scheduled for ${scheduleTime}`);
}

// Schedule recurring notifications
function scheduleRecurringReminder(title: string, text: string, interval: string, startTime?: Date) {
  const notification: ILocalNotification = {
    id: Math.floor(Math.random() * 1000000),
    title,
    text,
    every: interval, // 'minute', 'hour', 'day', 'week', 'month', 'year'
    firstAt: startTime || new Date(),
    sound: true,
    badge: 1,
    data: {
      type: 'recurring',
      interval
    }
  };

  LocalNotifications.schedule(notification);
  console.log(`Recurring notification scheduled (${interval})`);
}

// Medication reminder system
class MedicationReminder {
  private reminders: Map<string, number[]> = new Map();

  scheduleReminder(medicationName: string, times: string[], startDate: Date = new Date()) {
    const notificationIds: number[] = [];

    times.forEach((time, index) => {
      const [hours, minutes] = time.split(':').map(Number);
      const scheduleDate = new Date(startDate);
      scheduleDate.setHours(hours, minutes, 0, 0);

      const notificationId = Date.now() + index;
      const notification: ILocalNotification = {
        id: notificationId,
        title: 'Medication Reminder',
        text: `Time to take ${medicationName}`,
        every: 'day',
        firstAt: scheduleDate,
        sound: 'default',
        badge: 1,
        priority: 2,
        actions: ['Take', 'Snooze', 'Skip'],
        data: {
          type: 'medication',
          medication: medicationName,
          time: time
        }
      };

      LocalNotifications.schedule(notification);
      notificationIds.push(notificationId);
    });

    this.reminders.set(medicationName, notificationIds);
    console.log(`Scheduled ${times.length} reminders for ${medicationName}`);
  }

  async cancelReminder(medicationName: string) {
    const ids = this.reminders.get(medicationName);
    if (ids) {
      for (const id of ids) {
        await LocalNotifications.cancel(id);
      }
      this.reminders.delete(medicationName);
      console.log(`Cancelled reminders for ${medicationName}`);
    }
  }

  async listActiveReminders() {
    const active: { [key: string]: string[] } = {};
    
    for (const [medication, ids] of this.reminders) {
      const scheduledTimes: string[] = [];
      
      for (const id of ids) {
        const isScheduled = await LocalNotifications.isScheduled(id);
        if (isScheduled) {
          // Get notification details if needed
          scheduledTimes.push(`ID: ${id}`);
        }
      }
      
      if (scheduledTimes.length > 0) {
        active[medication] = scheduledTimes;
      }
    }
    
    return active;
  }
}

Push Notifications

Handle remote push notifications from various services with registration, event handling, and badge management.

/**
 * Push notification registration response
 */
interface RegistrationEventResponse {
  /** Registration token/ID for push service */
  registrationId: string;
  /** Registration type */
  registrationType: string;
}

/**
 * Push notification event response
 */
interface NotificationEventResponse {
  /** Notification message */
  message: string;
  /** Notification title */
  title?: string;
  /** Number of unread notifications */
  count: string;
  /** Additional notification data */
  additionalData: NotificationEventAdditionalData;
  /** Whether app was in foreground */
  foreground: boolean;
  /** Whether notification was cold start */
  coldstart: boolean;
}

/**
 * Additional push notification data
 */
interface NotificationEventAdditionalData {
  /** Custom payload data */
  [key: string]: any;
  /** Whether notification was dismissed */
  dismissed?: boolean;
  /** Action identifier (for interactive notifications) */
  actionCallback?: string;
}

/**
 * iOS-specific push options
 */
interface IOSPushOptions {
  /** Alert notifications enabled */
  alert?: boolean;
  /** Badge notifications enabled */
  badge?: boolean;
  /** Sound notifications enabled */
  sound?: boolean;
  /** Clear badge automatically */
  clearBadge?: boolean;
  /** Categories for interactive notifications */
  categories?: any[];
}

/**
 * Android-specific push options
 */
interface AndroidPushOptions {
  /** Sender ID for GCM/FCM */
  senderID?: string;
  /** Default small icon */
  icon?: string;
  /** Default icon color */
  iconColor?: string;
  /** Default sound */
  sound?: boolean;
  /** Default vibration */
  vibrate?: boolean;
  /** Clear notifications on app startup */
  clearNotifications?: boolean;
  /** Force show even when app is in foreground */
  forceShow?: boolean;
  /** Topics to subscribe to */
  topics?: string[];
}

/**
 * Cross-platform push options
 */
interface PushOptions {
  /** iOS-specific options */
  ios?: IOSPushOptions;
  /** Android-specific options */
  android?: AndroidPushOptions;
  /** Windows-specific options */
  windows?: any;
  /** Browser-specific options */
  browser?: any;
}

/**
 * Push notification object for managing push services
 */
interface PushObject {
  /**
   * Add event listener for push events
   * @param event Event name (registration, notification, error)
   * @returns Observable emitting push events
   */
  on(event: string): Observable<NotificationEventResponse | RegistrationEventResponse>;

  /**
   * Unregister from push notifications
   * @returns Promise indicating unregistration completion
   */
  unregister(): Promise<any>;

  /**
   * Set application icon badge number (iOS)
   * @param badgeNumber Badge number to set
   * @returns Promise indicating badge update completion
   */
  setApplicationIconBadgeNumber(badgeNumber: number): Promise<any>;

  /**
   * Get current application icon badge number (iOS)
   * @returns Promise resolving to current badge number
   */
  getApplicationIconBadgeNumber(): Promise<number>;

  /**
   * Finish handling notification (iOS background processing)
   */
  finish(): void;

  /**
   * Clear all notifications from notification center
   * @returns Promise indicating clear completion
   */
  clearAllNotifications(): Promise<any>;
}

/**
 * Push class for push notification management
 */
class Push {
  /**
   * Initialize push notifications
   * @param options Push configuration options
   * @returns PushObject instance
   */
  static init(options: PushOptions): PushObject;

  /**
   * Check if push notification permission is granted
   * @returns Promise resolving to permission status
   */
  static hasPermission(): Promise<{ isEnabled: boolean; }>;
}

Usage Examples:

import { Push, PushOptions, PushObject } from 'ionic-native';

// Initialize push notifications
function initializePush(): PushObject {
  const options: PushOptions = {
    android: {
      senderID: '123456789',
      icon: 'phonegap',
      iconColor: '#0000FF',
      sound: true,
      vibrate: true,
      clearNotifications: true,
      forceShow: true
    },
    ios: {
      alert: true,
      badge: true,
      sound: true,
      clearBadge: true
    }
  };

  const pushObject = Push.init(options);

  // Set up event handlers
  setupPushHandlers(pushObject);

  return pushObject;
}

// Set up push notification event handlers
function setupPushHandlers(pushObject: PushObject) {
  // Handle successful registration
  pushObject.on('registration').subscribe((registration) => {
    console.log('Device registered for push:', registration.registrationId);
    
    // Send registration token to your server
    sendTokenToServer(registration.registrationId);
  });

  // Handle incoming notifications
  pushObject.on('notification').subscribe((notification) => {
    console.log('Push notification received:', notification);
    
    if (notification.additionalData.foreground) {
      // App is in foreground - show custom UI
      showInAppNotification(notification);
    } else {
      // App was opened from notification
      handleNotificationOpen(notification);
    }

    // Finish processing (iOS)
    pushObject.finish();
  });

  // Handle registration errors
  pushObject.on('error').subscribe((error) => {
    console.error('Push notification error:', error);
  });
}

// Send registration token to server
async function sendTokenToServer(token: string) {
  try {
    await fetch('https://api.example.com/register-device', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-auth-token'
      },
      body: JSON.stringify({
        token,
        platform: Device.platform,
        uuid: Device.uuid
      })
    });
    
    console.log('Registration token sent to server');
  } catch (error) {
    console.error('Failed to send token to server:', error);
  }
}

// Handle notification when app is in foreground
function showInAppNotification(notification: any) {
  // Create custom in-app notification UI
  const notificationElement = document.createElement('div');
  notificationElement.className = 'in-app-notification';
  notificationElement.innerHTML = `
    <div class="notification-content">
      <h4>${notification.title}</h4>
      <p>${notification.message}</p>
      <button onclick="this.parentElement.parentElement.remove()">Close</button>
    </div>
  `;
  
  document.body.appendChild(notificationElement);
  
  // Auto-remove after 5 seconds
  setTimeout(() => {
    if (notificationElement.parentElement) {
      notificationElement.remove();
    }
  }, 5000);
}

// Handle notification tap when app was closed
function handleNotificationOpen(notification: any) {
  console.log('App opened from notification:', notification);
  
  // Navigate based on notification data
  if (notification.additionalData.type === 'message') {
    navigateToMessages(notification.additionalData.messageId);
  } else if (notification.additionalData.type === 'order') {
    navigateToOrder(notification.additionalData.orderId);
  }
}

// Push notification service class
class PushNotificationService {
  private pushObject: PushObject;
  private registrationToken: string = '';

  async initialize() {
    // Check permission
    const permission = await Push.hasPermission();
    if (!permission.isEnabled) {
      console.log('Push notifications not enabled');
      return;
    }

    this.pushObject = initializePush();
  }

  async updateBadgeCount(count: number) {
    if (this.pushObject && Device.platform === 'iOS') {
      await this.pushObject.setApplicationIconBadgeNumber(count);
    }
  }

  async clearBadge() {
    await this.updateBadgeCount(0);
  }

  async clearAllNotifications() {
    if (this.pushObject) {
      await this.pushObject.clearAllNotifications();
    }
  }

  async unregister() {
    if (this.pushObject) {
      await this.pushObject.unregister();
      console.log('Unregistered from push notifications');
    }
  }

  getRegistrationToken(): string {
    return this.registrationToken;
  }
}

OneSignal Integration

Advanced push notification service with segmentation, A/B testing, and analytics.

/**
 * OneSignal notification object
 */
interface OSNotification {
  /** Notification ID */
  notificationID?: string;
  /** Notification content */
  contents: any;
  /** Notification heading */
  headings?: any;
  /** Whether notification is app in focus */
  isAppInFocus: boolean;
  /** Shown notification */
  shown: boolean;
  /** Silent notification */
  silentNotification?: boolean;
  /** Additional data */
  additionalData?: any;
  /** Small icon (Android) */
  smallIcon?: string;
  /** Large icon (Android) */
  largeIcon?: string;
  /** Big picture (Android) */
  bigPicture?: string;
  /** Small icon accent color (Android) */
  smallIconAccentColor?: string;
  /** Launch URL */
  launchURL?: string;
  /** Sound file */
  sound?: string;
  /** LED color (Android) */
  ledColor?: string;
  /** Lock screen visibility (Android) */
  lockScreenVisibility?: number;
  /** Group key (Android) */
  groupKey?: string;
  /** Group message (Android) */
  groupMessage?: string;
  /** Action buttons */
  actionButtons?: any[];
  /** From projection ID */
  fromProjectNumber?: string;
  /** Priority */
  priority?: number;
  /** Raw payload */
  rawPayload?: string;
}

/**
 * OneSignal notification opened result
 */
interface OSNotificationOpenedResult {
  /** Action taken */
  action: {
    /** Action type (Opened, ActionTaken) */
    type: string;
    /** Action ID (for action buttons) */
    actionID?: string;
  };
  /** Notification object */
  notification: OSNotification;
}

/**
 * OneSignal user information
 */
interface OSUserInfo {
  /** Player ID */
  userId: string;
  /** Push token */
  pushToken: string;
  /** Email address */
  emailAddress?: string;
}

/**
 * OneSignal class for advanced push notifications
 */
class OneSignal {
  /**
   * Start OneSignal initialization
   * @param appId OneSignal App ID
   * @param googleProjectId Google Project ID (Android)
   * @returns OneSignal initialization object
   */
  static startInit(appId: string, googleProjectId?: string): any;

  /**
   * Handle notification received events
   * @returns Observable emitting received notifications
   */
  static handleNotificationReceived(): Observable<OSNotification>;

  /**
   * Handle notification opened events
   * @returns Observable emitting notification open events
   */
  static handleNotificationOpened(): Observable<OSNotificationOpenedResult>;

  /**
   * Complete OneSignal initialization
   */
  static endInit(): void;

  /**
   * Get user tags
   * @returns Promise resolving to tags object
   */
  static getTags(): Promise<any>;

  /**
   * Get user IDs
   * @returns Promise resolving to user info
   */
  static getIds(): Promise<OSUserInfo>;

  /**
   * Send tag key-value pair
   * @param key Tag key
   * @param value Tag value
   */
  static sendTag(key: string, value: string): void;

  /**
   * Send multiple tags
   * @param json Tags object
   */
  static sendTags(json: any): void;

  /**
   * Delete tag
   * @param key Tag key to delete
   */
  static deleteTag(key: string): void;

  /**
   * Delete multiple tags
   * @param keys Array of tag keys to delete
   */
  static deleteTags(keys: string[]): void;

  /**
   * Register for push notifications
   */
  static registerForPushNotifications(): void;

  /**
   * Enable vibration
   * @param enable Whether to enable vibration
   */
  static enableVibrate(enable: boolean): void;

  /**
   * Enable sound
   * @param enable Whether to enable sound
   */
  static enableSound(enable: boolean): void;

  /**
   * Set subscription status
   * @param enable Whether user is subscribed
   */
  static setSubscription(enable: boolean): void;

  /**
   * Post notification to other users
   * @param notificationObj Notification configuration
   * @returns Promise resolving to post result
   */
  static postNotification(notificationObj: OSNotification): Promise<any>;

  /**
   * Sync hashed email for email targeting
   * @param email User email address
   */
  static syncHashedEmail(email: string): void;

  /**
   * Prompt for location permission
   */
  static promptLocation(): void;

  /**
   * Clear all OneSignal notifications
   */
  static clearOneSignalNotifications(): void;

  /**
   * Set logging level
   * @param logLevel Log level
   * @param visualLevel Visual log level
   */
  static setLogLevel(logLevel: any, visualLevel: any): void;
}

Usage Examples:

import { OneSignal, OSNotification, OSNotificationOpenedResult } from 'ionic-native';

// Initialize OneSignal
function initializeOneSignal() {
  OneSignal.startInit('your-app-id', 'your-google-project-id')
    .handleNotificationReceived()
    .subscribe((notification: OSNotification) => {
      console.log('OneSignal notification received:', notification);
      handleNotificationReceived(notification);
    });

  OneSignal.startInit('your-app-id', 'your-google-project-id')
    .handleNotificationOpened()
    .subscribe((result: OSNotificationOpenedResult) => {
      console.log('OneSignal notification opened:', result);
      handleNotificationOpened(result);
    });

  OneSignal.endInit();
  
  // Configure settings
  OneSignal.enableVibrate(true);
  OneSignal.enableSound(true);
  OneSignal.registerForPushNotifications();
}

// Handle received notification
function handleNotificationReceived(notification: OSNotification) {
  if (notification.isAppInFocus) {
    // Show custom in-app notification
    showCustomNotification(notification);
  }
  
  // Update badge or UI based on notification
  updateAppState(notification.additionalData);
}

// Handle notification opened
function handleNotificationOpened(result: OSNotificationOpenedResult) {
  const { action, notification } = result;
  
  if (action.type === 'ActionTaken') {
    // Handle action button press
    handleNotificationAction(action.actionID, notification);
  } else {
    // Handle notification tap
    navigateFromNotification(notification.additionalData);
  }
}

// User segmentation and targeting
class OneSignalService {
  async setupUserProfile(userId: string, userProfile: any) {
    // Set user tags for segmentation
    const tags = {
      user_id: userId,
      user_type: userProfile.type,
      subscription_tier: userProfile.subscriptionTier,
      last_active: new Date().toISOString(),
      preferred_language: userProfile.language || 'en',
      age_group: this.getAgeGroup(userProfile.age),
      interests: userProfile.interests?.join(',') || ''
    };

    OneSignal.sendTags(tags);
    
    if (userProfile.email) {
      OneSignal.syncHashedEmail(userProfile.email);
    }

    console.log('OneSignal user profile configured');
  }

  async sendNotificationToUser(targetUserId: string, message: string, data?: any) {
    const notification = {
      contents: { en: message },
      include_external_user_ids: [targetUserId],
      data: data || {}
    };

    try {
      const result = await OneSignal.postNotification(notification);
      console.log('Notification sent successfully:', result);
      return result;
    } catch (error) {
      console.error('Failed to send notification:', error);
      throw error;
    }
  }

  async sendToSegment(segment: string, title: string, message: string, data?: any) {
    const notification = {
      headings: { en: title },
      contents: { en: message },
      filters: [
        { field: 'tag', key: 'user_type', relation: '=', value: segment }
      ],
      data: data || {}
    };

    try {
      const result = await OneSignal.postNotification(notification);
      console.log('Segment notification sent:', result);
      return result;
    } catch (error) {
      console.error('Failed to send segment notification:', error);
      throw error;
    }
  }

  updateUserActivity() {
    OneSignal.sendTag('last_active', new Date().toISOString());
  }

  setUserPreferences(preferences: any) {
    const tags: any = {};
    
    if (preferences.notifications !== undefined) {
      OneSignal.setSubscription(preferences.notifications);
    }
    
    if (preferences.sound !== undefined) {
      OneSignal.enableSound(preferences.sound);
      tags.sound_enabled = preferences.sound.toString();
    }
    
    if (preferences.vibrate !== undefined) {
      OneSignal.enableVibrate(preferences.vibrate);
      tags.vibrate_enabled = preferences.vibrate.toString();
    }

    if (Object.keys(tags).length > 0) {
      OneSignal.sendTags(tags);
    }
  }

  private getAgeGroup(age: number): string {
    if (age < 18) return 'under_18';
    if (age < 25) return '18_24';
    if (age < 35) return '25_34';
    if (age < 45) return '35_44';
    if (age < 55) return '45_54';
    return '55_plus';
  }

  async getUserInfo() {
    try {
      const [userInfo, tags] = await Promise.all([
        OneSignal.getIds(),
        OneSignal.getTags()
      ]);
      
      return { userInfo, tags };
    } catch (error) {
      console.error('Failed to get user info:', error);
      return null;
    }
  }
}

Toast Messages

Simple, non-intrusive messages that appear briefly at the bottom or top of the screen.

/**
 * Toast class for showing brief messages
 */
class Toast {
  /**
   * Show toast message with custom configuration
   * @param message Message to display
   * @param duration Duration ('short' or 'long')
   * @param position Position ('top', 'center', or 'bottom')
   * @returns Promise indicating toast completion
   */
  static show(message: string, duration: string, position: string): Promise<any>;

  /**
   * Show short toast at top of screen
   * @param message Message to display
   * @returns Promise indicating toast completion
   */
  static showShortTop(message: string): Promise<any>;

  /**
   * Show short toast at center of screen
   * @param message Message to display
   * @returns Promise indicating toast completion
   */
  static showShortCenter(message: string): Promise<any>;

  /**
   * Show short toast at bottom of screen
   * @param message Message to display
   * @returns Promise indicating toast completion
   */
  static showShortBottom(message: string): Promise<any>;

  /**
   * Show long toast at top of screen
   * @param message Message to display
   * @returns Promise indicating toast completion
   */
  static showLongTop(message: string): Promise<any>;

  /**
   * Show long toast at center of screen
   * @param message Message to display
   * @returns Promise indicating toast completion
   */
  static showLongCenter(message: string): Promise<any>;

  /**
   * Show long toast at bottom of screen
   * @param message Message to display
   * @returns Promise indicating toast completion
   */
  static showLongBottom(message: string): Promise<any>;
}

Dialogs

Native dialog boxes for alerts, confirmations, prompts, and custom interactions.

/**
 * Dialog prompt result
 */
interface DialogPromptResult {
  /** Button index pressed (1-based) */
  buttonIndex: number;
  /** Text input value (for prompt dialogs) */
  input1?: string;
}

/**
 * Dialogs class for native dialog boxes
 */
class Dialogs {
  /**
   * Show alert dialog
   * @param message Alert message
   * @param title Dialog title (optional)
   * @param buttonName Button text (default: 'OK')
   * @returns Promise indicating dialog completion
   */
  static alert(message: string, title?: string, buttonName?: string): Promise<any>;

  /**
   * Show confirmation dialog
   * @param message Confirmation message
   * @param title Dialog title (optional)
   * @param buttonLabels Array of button labels (default: ['OK', 'Cancel'])
   * @returns Promise resolving to button index (1-based)
   */
  static confirm(message: string, title?: string, buttonLabels?: Array<string>): Promise<number>;

  /**
   * Show prompt dialog
   * @param message Prompt message (optional)
   * @param title Dialog title (optional)
   * @param buttonLabels Array of button labels (optional)
   * @param defaultText Default input text (optional)
   * @returns Promise resolving to DialogPromptResult
   */
  static prompt(message?: string, title?: string, buttonLabels?: Array<string>, defaultText?: string): Promise<DialogPromptResult>;

  /**
   * Play device beep sound
   * @param times Number of beeps
   */
  static beep(times: number): void;
}

Usage Examples:

import { Toast, Dialogs } from 'ionic-native';

// Toast message examples
function showSuccessToast(message: string) {
  Toast.showShortBottom(`✓ ${message}`);
}

function showErrorToast(error: string) {
  Toast.showLongTop(`✗ ${error}`);
}

function showInfoToast(info: string) {
  Toast.showShortCenter(info);
}

// Dialog examples
async function confirmAction(message: string, actionName: string = 'Continue') {
  try {
    const buttonIndex = await Dialogs.confirm(
      message,
      'Confirm Action',
      [actionName, 'Cancel']
    );
    
    return buttonIndex === 1; // First button (actionName) was pressed
  } catch (error) {
    console.error('Dialog error:', error);
    return false;
  }
}

async function showUserAlert(title: string, message: string) {
  try {
    await Dialogs.alert(message, title, 'OK');
  } catch (error) {
    console.error('Alert error:', error);
  }
}

async function getUserInput(title: string, message: string, defaultValue: string = '') {
  try {
    const result = await Dialogs.prompt(
      message,
      title,
      ['Save', 'Cancel'],
      defaultValue
    );
    
    if (result.buttonIndex === 1) {
      return result.input1;
    }
    
    return null;
  } catch (error) {
    console.error('Prompt error:', error);
    return null;
  }
}

// Notification feedback manager
class NotificationFeedback {
  static showSuccess(message: string) {
    Toast.showShortBottom(`✓ ${message}`);
  }

  static showError(message: string) {
    Toast.showLongTop(`✗ ${message}`);
    Dialogs.beep(1);
  }

  static showWarning(message: string) {
    Toast.show(`⚠ ${message}`, 'long', 'center');
  }

  static showInfo(message: string) {
    Toast.showShortCenter(`ℹ ${message}`);
  }

  static async confirmDelete(itemName: string) {
    return await confirmAction(
      `Are you sure you want to delete "${itemName}"? This action cannot be undone.`,
      'Delete'
    );
  }

  static async confirmLogout() {
    return await confirmAction(
      'Are you sure you want to log out?',
      'Log Out'
    );
  }

  static async getTextInput(title: string, placeholder: string = '') {
    return await getUserInput(title, 'Please enter the text:', placeholder);
  }

  static async getPasswordInput(title: string = 'Enter Password') {
    return await getUserInput(title, 'Please enter your password:');
  }
}

// Advanced dialog patterns
class DialogService {
  static async showDeleteConfirmation(itemType: string, itemName: string) {
    const message = `This will permanently delete the ${itemType} "${itemName}". Are you sure?`;
    
    const buttonIndex = await Dialogs.confirm(
      message,
      'Delete Confirmation',
      ['Delete', 'Keep', 'Cancel']
    );
    
    switch (buttonIndex) {
      case 1: return 'delete';
      case 2: return 'keep';
      default: return 'cancel';
    }
  }

  static async showSaveChangesDialog() {
    const buttonIndex = await Dialogs.confirm(
      'You have unsaved changes. What would you like to do?',
      'Unsaved Changes',
      ['Save', 'Discard', 'Cancel']
    );
    
    switch (buttonIndex) {
      case 1: return 'save';
      case 2: return 'discard';
      default: return 'cancel';
    }
  }

  static async getRatingInput() {
    const result = await Dialogs.prompt(
      'Please rate this item from 1 to 5:',
      'Rating',
      ['Submit', 'Cancel'],
      '5'
    );
    
    if (result.buttonIndex === 1) {
      const rating = parseInt(result.input1 || '0');
      if (rating >= 1 && rating <= 5) {
        return rating;
      } else {
        await Dialogs.alert('Please enter a rating between 1 and 5.', 'Invalid Rating');
        return null;
      }
    }
    
    return null;
  }

  static playNotificationSound(urgency: 'low' | 'medium' | 'high') {
    const beepCounts = { low: 1, medium: 2, high: 3 };
    Dialogs.beep(beepCounts[urgency]);
  }
}

docs

analytics-monetization.md

camera-media.md

device-sensors.md

device-system.md

index.md

input-hardware.md

location-maps.md

network-communication.md

notifications-ui.md

security-auth.md

social-sharing.md

storage-files.md

tile.json