Schedule local notifications and handle remote push with APNs.
Notifications Overview
# Frameworks: UserNotifications, UserNotificationsUI
# Import: import UserNotifications
# Permissions: Not automatically requested - must ask userLocal Notifications
import UserNotifications
class LocalNotificationManager: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
static let shared = LocalNotificationManager()
@Published var pendingNotifications: [UNNotificationRequest] = []
@Published var deliveredNotifications: [UNNotification] = []
private override init() {
super.init()
UNUserNotificationCenter.current().delegate = self
}
// Request permission
func requestAuthorization() async -> Bool {
do {
let granted = try await UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .badge, .sound, .criticalAlert, .provisional]
)
return granted
} catch {
print("Notification permission error: \(error)")
return false
}
}
// Check authorization status
func getAuthorizationStatus() async -> UNAuthorizationStatus {
let settings = await UNUserNotificationCenter.current().notificationSettings()
return settings.authorizationStatus
}
// Schedule notification
func scheduleNotification(
id: String,
title: String,
body: String,
date: Date,
repeats: Bool = false,
userInfo: [AnyHashable: Any] = [:],
sound: UNNotificationSound = .default,
categoryIdentifier: String? = nil
) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = sound
content.userInfo = userInfo
if let category = categoryIdentifier {
content.categoryIdentifier = category
}
let trigger: UNNotificationTrigger
if repeats {
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
} else {
let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
}
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Schedule error: \(error)")
}
}
}
// Schedule with time interval
func scheduleAfter(
id: String,
title: String,
body: String,
timeInterval: TimeInterval,
userInfo: [AnyHashable: Any] = [:]
) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.userInfo = userInfo
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error { print("Schedule error: \(error)") }
}
}
// Cancel notification
func cancel(id: String) {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [id])
}
// Cancel all
func cancelAll() {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
// Get pending
func fetchPending() async {
let requests = await UNUserNotificationCenter.current().pendingNotificationRequests()
await MainActor.run { self.pendingNotifications = requests }
}
// Get delivered
func fetchDelivered() async {
let notifications = await UNUserNotificationCenter.current().deliveredNotifications()
await MainActor.run { self.deliveredNotifications = notifications }
}
// Clear delivered
func clearDelivered() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
deliveredNotifications = []
}
// Badge management
func setBadge(_ count: Int) {
UNUserNotificationCenter.current().setBadgeCount(count) { error in
if let error = error { print("Badge error: \(error)") }
}
}
// Delegate: handle notification when app is in foreground
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
// Show banner even in foreground
completionHandler([.banner, .list, .sound, .badge])
}
// Delegate: handle notification tap
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
let actionIdentifier = response.actionIdentifier
// Handle custom actions
switch actionIdentifier {
case UNNotificationDefaultActionIdentifier:
print("Tapped notification")
// Navigate based on userInfo
case UNNotificationDismissActionIdentifier:
print("Dismissed notification")
default:
print("Custom action: \(actionIdentifier)")
// Handle custom action
}
completionHandler()
}
}Notification Categories & Actions
// Define categories with actions
func setupCategories() {
// Action: Reply
let replyAction = UNTextInputNotificationAction(
identifier: "REPLY_ACTION",
title: "Reply",
options: [],
textInputButtonTitle: "Send",
textInputPlaceholder: "Type your reply..."
)
// Action: Like
let likeAction = UNNotificationAction(
identifier: "LIKE_ACTION",
title: "❤️ Like",
options: [.foreground]
)
// Action: Dismiss
let dismissAction = UNNotificationAction(
identifier: "DISMISS_ACTION",
title: "Dismiss",
options: [.destructive, .authenticationRequired]
)
// Category: Message
let messageCategory = UNNotificationCategory(
identifier: "MESSAGE_CATEGORY",
actions: [replyAction, likeAction, dismissAction],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "New message",
options: [.customDismissAction]
)
// Category: Reminder
let reminderCategory = UNNotificationCategory(
identifier: "REMINDER_CATEGORY",
actions: [dismissAction],
intentIdentifiers: [],
options: []
)
UNUserNotificationCenter.current().setNotificationCategories([
messageCategory, reminderCategory
])
}Rich Notifications (Attachments)
func sendRichNotification(
id: String,
title: String,
body: String,
imageURL: URL,
timeInterval: TimeInterval
) async {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
// Download and attach image
do {
let (data, _) = try await URLSession.shared.data(from: imageURL)
let tempURL = FileManager.default.temporaryDirectory
.appendingPathComponent("notification_\(UUID().uuidString).jpg")
try data.write(to: tempURL)
let attachment = try UNNotificationAttachment(
identifier: "image",
url: tempURL,
options: [UNNotificationAttachmentOptionsTypeHintKey: "image/jpeg"]
)
content.attachments = [attachment]
} catch {
print("Attachment error: \(error)")
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
try? await UNUserNotificationCenter.current().add(request)
}Remote Push Notifications (APNs)
import UserNotifications
class PushNotificationManager: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
static let shared = PushNotificationManager()
@Published var deviceToken: String?
@Published var pushPayload: [AnyHashable: Any]?
private override init() {
super.init()
UNUserNotificationCenter.current().delegate = self
}
// Register for remote notifications
func registerForRemoteNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
// Handle device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
self.deviceToken = token
print("APNs Device Token: \(token)")
// Send to your server
sendTokenToServer(token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
private func sendTokenToServer(_ token: String) {
// POST to your backend
Task {
try? await APIClient.shared.registerDeviceToken(token)
}
}
// Handle incoming push (foreground)
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
pushPayload = notification.request.content.userInfo
completionHandler([.banner, .list, .sound, .badge])
}
// Handle push tap (background/terminated)
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
pushPayload = response.notification.request.content.userInfo
handlePushNavigation(response.notification.request.content.userInfo)
completionHandler()
}
// Handle app launch from push
func handleLaunchFromPush(_ userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo else { return }
pushPayload = userInfo
handlePushNavigation(userInfo)
}
private func handlePushNavigation(_ userInfo: [AnyHashable: Any]) {
// Navigate based on payload
if let route = userInfo["route"] as? String {
// Use NavigationRouter or NotificationCenter to navigate
NotificationCenter.default.post(
name: .pushNavigation,
object: nil,
userInfo: ["route": route]
)
}
}
}
extension Notification.Name {
static let pushNavigation = Notification.Name("pushNavigation")
}APNs Payload Structure
// Silent push (background refresh)
{
"aps": {
"content-available": 1
},
"data": {
"sync": true
}
}
// Alert push
{
"aps": {
"alert": {
"title": "New Message",
"subtitle": "From John",
"body": "Hello! How are you?",
"loc-key": "MESSAGE_RECEIVED",
"loc-args": ["John"]
},
"badge": 5,
"sound": "default",
"thread-id": "chat_123",
"category": "MESSAGE_CATEGORY",
"mutable-content": 1
},
"route": "chat/123",
"customData": "anything"
}Notification Service Extension (Rich Push)
// Create: File → New → Target → Notification Service Extension
// Import: UserNotifications
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
guard let bestAttemptContent = bestAttemptContent,
let imageUrlString = bestAttemptContent.userInfo["image-url"] as? String,
let imageUrl = URL(string: imageUrlString) else {
contentHandler(bestAttemptContent ?? request.content)
return
}
// Download image
URLSession.shared.downloadTask(with: imageUrl) { location, response, error in
guard let location = location,
let data = try? Data(contentsOf: location),
let attachment = try? UNNotificationAttachment(
identifier: "image",
url: location,
options: nil
) else {
contentHandler(bestAttemptContent)
return
}
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
}.resume()
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}Notification Content Extension (Custom UI)
// Create: File → New → Target → Notification Content Extension
// Info.plist: UNNotificationExtensionCategory = "MESSAGE_CATEGORY"
// UNNotificationExtensionDefaultContentHidden = YES
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var avatarImageView: UIImageView!
func didReceive(_ notification: UNNotification) {
let content = notification.request.content
messageLabel.text = content.body
if let avatarUrl = content.userInfo["avatar-url"] as? String,
let url = URL(string: avatarUrl) {
// Load image
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
DispatchQueue.main.async {
self.avatarImageView.image = UIImage(data: data)
}
}
}.resume()
}
}
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
if response.actionIdentifier == "REPLY_ACTION",
let textResponse = response as? UNTextInputNotificationResponse {
// Send reply
sendReply(textResponse.userText)
completion(.dismiss)
} else {
completion(.doNotDismiss)
}
}
}Testing Notifications
// Unit test
class NotificationTests: XCTestCase {
func testLocalNotificationScheduling() async {
let manager = LocalNotificationManager.shared
// Request permission
let granted = await manager.requestAuthorization()
XCTAssertTrue(granted)
// Schedule
let date = Date().addingTimeInterval(5)
manager.scheduleNotification(
id: "test",
title: "Test",
body: "Test body",
date: date
)
// Wait and verify
try await Task.sleep(nanoseconds: 6_000_000_000)
await manager.fetchPending()
XCTAssertTrue(manager.pendingNotifications.contains { $0.identifier == "test" })
}
}Try It
Request permission. Schedule local notification. Add actions. Test remote push with APNs. Create notification service extension.
# Test APNs: Use Pusher, Knuff, or Xcode's push simulator
# Xcode 11.4+: Simulator supports remote pushNotification system
- Build LocalNotificationManager with full CRUD
- Add categories with custom actions (reply, like, dismiss)
- Implement rich notifications with image attachments
- Set up APNs and register for remote notifications
- Create Notification Service Extension for rich push
- Create Notification Content Extension for custom UI
- Handle navigation from push taps
- Test with foreground, background, terminated states
Local: UNUserNotificationCenter with triggers. Remote: APNs with device token. Categories enable actions. Service Extension modifies content before display. Content Extension provides custom UI. Handle all app states: foreground, background, terminated.
Resources
- UserNotifications: https://developer.apple.com/documentation/usernotifications
- APNs: https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server
- Notification Extensions: https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension