Local Notifications with Swift 4

import UserNotifications
let notificationCenter = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
notificationCenter.getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
// Notifications not allowed
}
}

Create a notification request:

func scheduleNotification(notificationType: String) {

let content = UNMutableNotificationContent() // Содержимое уведомления

content.title = notificationType
content.body = "This is example how to create " + notificationType Notifications"
content.sound = UNNotificationSound.default
content.badge = 1
}

Notification Trigger

Sending a calendar based notification

let date = Date(timeIntervalSinceNow: 3600)
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let date = Date(timeIntervalSinceNow: 3600)
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let date = Date(timeIntervalSinceNow: 3600)
let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

Send notification by location

Sending a time notification

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

Schedule:

let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let okAction = UIAlertAction(title: "OK", style: .default) { (action) in

self.appDelegate?.scheduleNotification(notificationType: notificationType)
}
UIApplication.shared.applicationIconBadgeNumber = 0
extension AppDelegate: UNUserNotificationCenterDelegate {

}

In both cases, you need to call the completion handler to complete

func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

}
completionHandler([.alert, .sound])
notificationCenter.delegate = self

Notification processing

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {

if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}

completionHandler()
}

Local Notification with Action

1. Define the action (s) of the notification:

let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "Delete", title: "Delete", options: [.destructive])

2. Creating a category for action

let userActions = "User Actions"
let category = UNNotificationCategory(identifier: userActions, actions: [snoozeAction, deleteAction], intentIdentifiers: [], options: [])

3. Category registration in the notification center

notificationCenter.setNotificationCategories([category])
content.categoryIdentifier = userActions
func scheduleNotification(notificationType: String) {

let content = UNMutableNotificationContent() // Содержимое уведомления
let userActions = "User Actions"

content.title = notificationType
content.body = "This is example how to create " + notificationType
content.sound = UNNotificationSound.default
content.badge = 1
content.categoryIdentifier = userActions

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}

let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "Delete", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: userActions, actions: [snoozeAction, deleteAction], intentIdentifiers: [], options: [])

notificationCenter.setNotificationCategories([category])
}
switch response.actionIdentifier {
case UNNotificationDismissActionIdentifier:
print("Dismiss Action")
case UNNotificationDefaultActionIdentifier:
print("Default")
case "Snooze":
print("Snooze")
scheduleNotification(notificationType: "Reminder")
case "Delete":
print("Delete")
default:
print("Unknown action")
}

Refactoring

import Foundation
import UserNotifications

class Notifications: NSObject, UNUserNotificationCenterDelegate {

}
func notificationRequest() {

let options: UNAuthorizationOptions = [.alert, .sound, .badge]

notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
}
let notifications = Notifications()

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

notifications.notificationCenter.delegate = notifications
notifications.notificationRequest()

return true
}
let notifications = Notifications()
let okAction = UIAlertAction(title: "OK", style: .default) { (action) in

self.notifications.scheduleNotification(notificationType: notificationType)
}

Software Developer, Tech enthusiastic, iOS #swift \\ Android #kotlin

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store