Local notifications in Swift allow apps to deliver messages or reminders to users without requiring a network connection. These notifications are triggered by the app itself, based on specific criteria such as time, location, or user interaction.
This guide provides a comprehensive overview of local notifications in Swift, with definitions, examples, and best practices.

1. What Are Local Notifications?
A local notification is a way for an app to alert the user about an event, task, or update using the device’s notification system. Unlike push notifications, local notifications don’t require a server or external data—they’re managed entirely by the app on the device.
Key Features of Local Notifications:
• Triggered by the app.
• No internet connection required.
• Supports custom content (e.g., text, sound, and badges).
2. Key Components of Local Notifications
2.1 UNUserNotificationCenter
The central object for managing notification-related activities.
• Registers the app for notifications.
• Schedules and delivers notifications.
2.2 UNNotificationRequest
Represents a notification request containing:
• Content: The message, sound, and badge.
• Trigger: The condition for displaying the notification.
2.3 UNNotificationContent
Defines the content of the notification, such as the title, body, and sound.
2.4 UNNotificationTrigger
Determines when the notification will be displayed. Types include:
• Time-based trigger (e.g., after 10 seconds).
• Calendar-based trigger (e.g., specific date and time).
• Location-based trigger (e.g., entering a specific area).
3. Steps to Implement Local Notifications in Swift
Step 1: Request Notification Permission
Apps need user permission to send notifications.
import UserNotifications
func requestNotificationPermission() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("Permission granted!")
} else {
print("Permission denied.")
}
}
}
Step 2: Create Notification Content
Define the title, subtitle, body, and other properties of the notification.
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "Don't forget to complete your task!"
content.sound = UNNotificationSound.default
content.badge = 1
Step 3: Define a Trigger
Specify the condition for triggering the notification.
Time-Based Trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
Calendar-Based Trigger
var dateComponents = DateComponents()
dateComponents.hour = 9
dateComponents.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
Location-Based Trigger
import CoreLocation
let center = CLLocationCoordinate2D(latitude: 37.334722, longitude: -122.008889)
let region = CLCircularRegion(center: center, radius: 100, identifier: "ApplePark")
region.notifyOnEntry = true
region.notifyOnExit = false
let trigger = UNLocationNotificationTrigger(region: region, repeats: false)
Step 4: Create and Schedule the Notification Request
Combine the content and trigger into a notification request and add it to the notification center.
let request = UNNotificationRequest(identifier: "ReminderNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error scheduling notification: \(error.localizedDescription)")
} else {
print("Notification scheduled!")
}
}
4. Handling Notifications When the App is Running
Notifications are displayed even if the app is in the foreground. To handle them:
1. Conform to UNUserNotificationCenterDelegate.
2. Implement
Delegate Methods to handle foreground notifications.
Step 1: Set the Delegate
Assign the delegate in your app’s didFinishLaunchingWithOptions.
UNUserNotificationCenter.current().delegate = self
Step 2: Implement Delegate Methods
Display Notification in Foreground
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Display the notification even when the app is active
completionHandler([.alert, .sound, .badge])
}
}
Handle User Interaction
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Handle actions when the user interacts with the notification
let identifier = response.notification.request.identifier
print("Notification received with identifier: \(identifier)")
completionHandler()
}
5. Adding Custom Actions to Notifications
Local notifications can have custom actions, such as “Mark as Done” or “Snooze”.
Step 1: Define Actions
let doneAction = UNNotificationAction(identifier: "MARK_DONE", title: "Mark as Done", options: [])
let snoozeAction = UNNotificationAction(identifier: "SNOOZE", title: "Snooze", options: [])
Step 2: Create a Category
let category = UNNotificationCategory(identifier: "TASK_CATEGORY", actions: [doneAction, snoozeAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
Step 3: Assign the Category to Content
content.categoryIdentifier = "TASK_CATEGORY"
Step 4: Handle the Actions
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier {
case "MARK_DONE":
print("Task marked as done!")
case "SNOOZE":
print("Task snoozed!")
default:
break
}
completionHandler()
}
6. Best Practices for Local Notifications
1. Respect User Privacy: Always explain why notifications are needed in your app.
2. Avoid Overusing Notifications: Too many notifications can annoy users.
3. Test Thoroughly: Ensure all triggers and actions work correctly in different app states.
4. Use Badges Wisely: Keep badge counts accurate and relevant.
5. Provide Customization Options: Allow users to customize notification preferences.
7. Example: Task Reminder App
Here’s a complete example of a task reminder app that schedules a notification at a specific time.
import SwiftUI
import UserNotifications
struct ContentView: View {
@State private var reminderTime = Date()
var body: some View {
VStack {
DatePicker("Set Reminder Time:", selection: $reminderTime, displayedComponents: .hourAndMinute)
.padding()
Button("Schedule Reminder") {
scheduleNotification(at: reminderTime)
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.onAppear {
requestNotificationPermission()
}
}
func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("Notification permission granted!")
} else {
print("Permission denied.")
}
}
}
func scheduleNotification(at time: Date) {
let content = UNMutableNotificationContent()
content.title = "Task Reminder"
content.body = "It's time to complete your task!"
content.sound = .default
var dateComponents = Calendar.current.dateComponents([.hour, .minute], from: time)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "TaskReminder", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error scheduling notification: \(error.localizedDescription)")
} else {
print("Notification scheduled for \(time)")
}
}
}
}
8. Conclusion
Local notifications in Swift are a powerful way to engage users and provide value in your app. With proper implementation and user-focused design, you can create seamless and effective reminders, updates, and alerts. Experiment with the code examples provided here and build feature-rich iOS apps! 🚀
Comments