Skip to content

Local Notifications ​

Local notifications allow your app to alert users at specified times when the app is in the background or not running. This implementation provides two main functionalities:

  • Requesting notification permissions from users
  • Scheduling time-based local notifications

Implementation ​

  1. Create a Swift File
    • In Xcode, go to File > New > File From Template...
    • Select Swift File, name it NotificationManager.swift, and paste the following code:
swift
import Foundation
import UserNotifications

class NotificationManager {

    // This function requests notification permission from the user
    func requestNotificationAuthorization(completion: @escaping (Bool) -> Void) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                print("Notification authorization granted")
            } else {
                print("Notification authorization denied")
            }
            completion(granted)
        }
    }

    // This function schedules a local notification in x seconds
    func scheduleNotificationInSeconds(title: String, body: String, sound: String, identifier: String = "com.example.enclose", seconds: Double) {
        let center = UNUserNotificationCenter.current()
        center.removePendingNotificationRequests(withIdentifiers: [identifier])

        let content = UNMutableNotificationContent()
        content.title = title
        content.body = body
        content.sound = UNNotificationSound(named: UNNotificationSoundName(sound))
        content.interruptionLevel = .active

        // Prepare "trigger" and "request"
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: seconds, repeats: false)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        // Schedule the local notification
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("Error scheduling notification: \(error.localizedDescription)")
            } else {
                print("Notification scheduled successfully")
            }
        }
    }
}
  1. Integrate with Your View Controller
    • In your MainViewController.swift file, add these methods to bridge between JavaScript and native notifications:
swift
// This function returns the status of notifications authorization
@objc func getNotificationsAuthorizationStatus(_ params: [String: String]) {
    var javaScript = ""
    let notificationManager = NotificationManager()
    notificationManager.requestNotificationAuthorization { granted in
        if granted {
            Task {
                if let successCallback = params["successCallback"] {
                    javaScript = "\(successCallback)(true);"
                    self.evaluateJavascript(javaScript: javaScript)
                }
            }
        } else {
            if let successCallback = params["successCallback"] {
                javaScript = "\(successCallback)(false);"
                self.evaluateJavascript(javaScript: javaScript)
            }
        }
    }
}

// This method will schedule a local notification that will fire in X seconds
@objc func scheduleNotificationInSeconds(_ params: [String: String]) {

    let secondsDoubleValue = Double(params["seconds"] ?? "5")
    let notificationManager = NotificationManager()

    notificationManager.scheduleNotificationInSeconds(
        title: params["title"] ?? "Title",
        body: params["body"] ?? "Body",
        sound: params["sound"] ?? "default",
        identifier: params["identifier"] ?? "com.example.enclose",
        seconds: secondsDoubleValue ?? 5
    )
}
  1. Using the Notifications in JavaScript
    • To check check/request notification permission call getNotificationsAuthorizationStatus method:
javascript
// Check if our app has authorization to send notifications
enClose({
    nativeCall: 'getNotificationsAuthorizationStatus',
    // callback function will receive a boolean value
    successCallback: ''
});
  • To schedule a local notification that will trigger in X seconds call scheduleNotificationInSeconds method:
javascript
// Schedule a local notification in 10 seconds
const randomString = Math.random().toString(36).substring(2,7);

enClose({
    nativeCall: 'scheduleNotificationInSeconds',
    data: {
        title: 'Notification title goes here',
        body: 'Notification body goes here',
        sound: 'default',
        seconds: 10,
        identifier: randomString
    }
});

Advanced Usage ​

  • To use custom sounds, add your MP3 files to the Xcode project and pass the filename (without extension) in the sound parameter
  • To cancel a pending notification, store the identifier and implement a cancellation method
  • For recurring notifications, modify the trigger to use repeats: true with appropriate time intervals