Swift: Implement UserNotifications (Local Notification & Remote Notification)


import UserNotifications

/// Register user notification
func registerUserNotification() {
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (permitted, error) in
    if (error != nil) {
      debugPrint("User notification allow status:\(String(describing: error?.localizedDescription))")
    }
  debugPrint("User notification allow status:\(permitted)")
  }
 UIApplication.shared.registerForRemoteNotifications()
}
/// Get UserNotification Permission
func userNotificationAuthorized() {
  UNUserNotificationCenter.current().getNotificationSettings() { (access) in

  switch access.authorizationStatus {
  case .authorized:
   self.println("authorized")
  case .denied:
   self.println("get Permission")
  case .notDetermined:
   self.println("something vital went wrong here")
  }
 }
}

/// Fire local Notification with message string
func requestRichNotification(category categoryName: String, notification identifier: String, from service: String, body message: String, userInfo: [String: Any]!) {

  UNUserNotificationCenter.current().getNotificationSettings { (settings) in
  if settings.authorizationStatus == .authorized {

    // Create Notification Content
    let notificationContent = UNMutableNotificationContent()

    // Configure Notification Content
    notificationContent.title = "" //appName
    notificationContent.subtitle = service
    notificationContent.body = message
    notificationContent.categoryIdentifier = categoryName
    notificationContent.sound = UNNotificationSound.default()

/*
// If you want to attach any image to show in local notification
let url = Bundle.main.url(forResource: "notificationImage", withExtension: ".jpg")
do {
let attachment = try? UNNotificationAttachment(identifier: requestIdentifier, url: url!, options: nil)
content.attachments = [attachment!]
}
*/

    let triggerAfter = UNTimeIntervalNotificationTrigger(timeInterval: 0.5, repeats: false) // Add Trigger schudled notification

    // Create Notification Request
    let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: triggerAfter)

    // Add Request to User Notification Center
    UNUserNotificationCenter.current().add(request) { (error) in
     if let error = error {
       debugPrint("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
     } else {
       debugPrint("Local notification updated.")
     }
   }
  } else {
   // Do nothing.
  }

 }
}

In appDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   UNUserNotificationCenter.current().delegate = self
   return true
}

// MARK: - UserNotificationCenter Delegates
extension AppDelegate: UNUserNotificationCenterDelegate {

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
   // UserNotification failed to register
   println("I am not available in simulator: \(error.localizedDescription)")
 }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

   #if (arch(i386) || arch(x86_64)) && os(iOS)
    // FIXME: - Static devicetoken for simulator
    AppInfo.shared.deviceToken = "Simulator-\(AppInfo.shared.deviceName)"
   #else
    //Get Remote notification device token here.
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    //Saving push notification Device token
   #endif

   // println("deviceToken: \(deviceTokenString)")
 }

 /// Push notification.
 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
   /// Handle push notification. here
 }
// For handling tap and user actions
 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

  if response.notification.request.content.categoryIdentifier == "NotificationServiceCategory" {

    if response.notification.request.identifier == "localNotification" {
      // let _ = response.notification.request.content.userInfo
    } else {
   // Do something.
   }
  } else {
   // Do something.
  }

 }
 //for displaying notification when app is in foreground
 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

  //If you don't want to show notification when app is open, do something here else and make a return here.
  //Even you you don't implement this delegate method, you will not see the notification on the specified controller. So, you have to implement this delegate and make sure the below line execute. i.e. completionHandler.

  completionHandler([.alert, .badge, .sound])
 }
}

– How to make an iOS App
ktrkathir

Author: Kathiresan Murugan

Associate Technical Lead - iOS

Leave a comment