Skip to content

Instantly share code, notes, and snippets.

@EQuimper
Created September 24, 2018 20:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EQuimper/a22400ecbd0ff1ec84bc009bf011bb71 to your computer and use it in GitHub Desktop.
Save EQuimper/a22400ecbd0ff1ec84bc009bf011bb71 to your computer and use it in GitHub Desktop.
Sending local notification in swift
//
// NotificationPublisher.swift
// LocalNotificationTutorial
//
// Created by Emanuel Quimper on 2018-09-24.
// Copyright © 2018 Emanuel Quimper. All rights reserved.
//
import UserNotifications
import UIKit
class NotificationPublisher: NSObject {
func sendNotification(title: String, subtitle: String, body: String, badge: Int?, delayInterval: Int?) {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = title
notificationContent.subtitle = subtitle
notificationContent.body = body
var delayTimeTrigger: UNTimeIntervalNotificationTrigger?
if let delayInterval = delayInterval {
delayTimeTrigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(delayInterval), repeats: false)
}
if let badge = badge {
var currentBadgeCount = UIApplication.shared.applicationIconBadgeNumber
currentBadgeCount += badge
notificationContent.badge = NSNumber(integerLiteral: currentBadgeCount)
}
notificationContent.sound = UNNotificationSound.default
UNUserNotificationCenter.current().delegate = self
let request = UNNotificationRequest(identifier: "TestLocalNotification", content: notificationContent, trigger: delayTimeTrigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print(error.localizedDescription)
}
}
}
}
extension NotificationPublisher: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("The notification is about to be presented")
completionHandler([.badge, .sound, .alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let identifier = response.actionIdentifier
switch identifier {
case UNNotificationDismissActionIdentifier:
print("Notification was dismissed")
completionHandler()
case UNNotificationDefaultActionIdentifier:
print("The user opened the app from the notification")
completionHandler()
default:
print("The default case was called")
completionHandler()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment