- SwiftUI - Home
- SwiftUI - Overview
- SwiftUI vs UIkit
- SwiftUI Environment
- SwiftUI - Environment Setup
- SwiftUI - Basic Components
- SwiftUI - Building First Application
- SwiftUI Views
- SwiftUI - Views
- SwiftUI - Customize Text View
- SwiftUI - Custom Image View
- SwiftUI - Stacks
- SwiftUI Drawing Shapes
- SwiftUI - Shapes
- SwiftUI - Drawing line
- SwiftUI - Drawing Rectangle
- SwiftUI - Drawing Rounded Rectangle
- SwiftUI - Drawing Triangle
- SwiftUI - Drawing Circle
- SwiftUI - Drawing Star
- SwiftUI - Drawing Polygon
- SwiftUI - Drawing Pie chart
- SwiftUI - Using built-in shapes
- SwiftUI - Text
- SwiftUI - Text View
- SwiftUI - Text Input and Output
- SwiftUI - Color
- SwiftUI - Color
- SwiftUI - Colorpicker
- SwiftUI - Gradients
- SwiftUI - Adjust Color
- SwiftUI - Effects
- SwiftUI - Effects
- SwiftUI - Blend Effect
- SwiftUI - BLur Effect
- SwiftUI - Shadow Effect
- SwiftUI - Hover Effect
- SwiftUI - Animations
- SwiftUI - Animations
- SwiftUI - Creating Animations
- SwiftUI - Creating an Explicit Animation
- SwiftUI - Multiple Animations
- SwiftUI - Transitions
- SwiftUI - Asymmetric Transition
- SwiftUI - Custom Transition
- SwiftUI - Image
- SwiftUI - Images
- SwiftUI - Image as Background
- SwiftUI - Rotating Image
- SwiftUI - Media
- SwiftUI - View Layout
- SwiftUI - View Layout
- SwiftUI - View Size
- SwiftUI - View Spacing
- SwiftUI - View Padding
- SwiftUI - UI Controls
- SwiftUI - UI Controls
- SwiftUI - Button
- SwiftUI - CheckBox
- SwiftUI - Menubar
- SwiftUI - Toolbar
- SwiftUI - Search Bar
- SwiftUI - TextField
- SwiftUI - Slider
- SwiftUI - Toggle
- SwiftUI - Pickers
- SwiftUI - Menus
- SwiftUI - List & Tables
- SwiftUI - Lists
- SwiftUI - Static List
- SwiftUI - Dynamic List
- SwiftUI - Customize List
- SwiftUI - Tables
- SwiftUI - Forms
- SwiftUI - Forms
- SwiftUI - Breaking Forms in Sections
- SwiftUI - Event Handling
- SwiftUI - Event Handling
- SwiftUI - Gesture
- SwiftUI - Clipboard
- SwiftUI - Drag and Drop
- SwiftUI - Focus
- SwiftUI - Alert
- SwiftUI - Miscellaneous
- SwiftUI - Containers
- SwiftUI - Navigation
- SwiftUI - Notifications
- SwiftUI - Cross-Platform UI
- SwiftUI - Data
- SwiftUI - Accessibility
- SwiftUI - Framework Integration
- SwiftUI - Framework Integration
- SwiftUI - Interfacing with UIKit
- SwiftUI - Creating macOS App
- SwiftUI Useful Resources
- SwiftUI - Useful Resources
- SwiftUI - Discussion
SwiftUI- Notification
A notification is a message or alert sent to users to inform them of new information, updates, or events related to an application or service. Notifications can appear on a device's lock screen, in the notification center, or as banners or alerts, depending on the system and settings.
Types of Notifications
In SwiftUI, notifications are of two types:
Local Notifications: These are scheduled and triggered locally on the device without needing an internet connection. For instance, a reminder app might use a local notification to alert a user about an upcoming event.
Push (Remote) Notifications: These are sent from a server to the device, often through a service like Apple Push Notification Service (APNs) for iOS or Firebase Cloud Messaging (FCM) for Android. For example, a social media app might send a push notification to notify a user about a new message.
How Notification Works?
The working of notification is explained in the following steps:
Permission Request: Apps request permission from users to show notifications.
Triggering: A notification is triggered either by the app (local) or a server (push).
Display: The notification is shown on the device as a banner, sound, or badge.
Interaction: Users may interact with the notification by tapping it, which opens the app or performs an action (e.g., reply to a message).
Local Notification
A local notification in SwiftUI refers to a notification that is triggered by the app itself, typically without requiring an internet connection. Local notifications can be scheduled to appear at a certain time or after a specific event, and they can include content like titles, messages, sounds, and badges.
These notifications are managed locally on the device, which means the app does not rely on an external server to trigger them.
Example
The following SwiftUI program is used to create local notification.
import SwiftUI
import UserNotifications
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onAppear {
// Request notification permission when the app appears
requestNotificationPermission()
}
}
}
// Request permission to show notifications
func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Notification permission granted")
} else if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
// Function to schedule a local notification after 5 seconds
func scheduleLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "Reminder!"
content.body = "This is a local notification from SwiftUI."
content.sound = .default
// Trigger the notification 5 seconds later
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// Create a notification request
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// Add the notification request to the notification center
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error scheduling notification: \(error.localizedDescription)")
} else {
print("Notification scheduled successfully!")
}
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// This function is called when the app finishes launching
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
// Handle notification when app is in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Show the notification with a banner and sound
completionHandler([.banner, .sound])
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Local Notification Example").font(.title).padding()
// Button to schedule a local notification
Button(action: {
// Call the function to schedule the notification
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.scheduleLocalNotification()
}
}) {
Text("Schedule Notification")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}.padding()
}
}
Remote Notification
Push (Remote) Notifications are messages sent from a server to a user's device, even when the app is not running in the foreground. Unlike local notifications, which are triggered by the app itself, push notifications are initiated from an external server, typically through services like Apple Push Notification Service (APNs) for iOS and Firebase Cloud Messaging (FCM) for Android.
Example
The following SwiftUI program is used to create push notification.
import SwiftUI
import UserNotifications
import UIKit
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onAppear {
// Request notification permission on launch
requestPushNotificationPermission()
}
}
}
// Request push notification permission
func requestPushNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Push notification permission granted")
} else if let error = error {
print("Error requesting permission: \(error.localizedDescription)")
}
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Request push notification permission
requestPushNotificationPermission()
// Register for remote notifications
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Handle device token here
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
print("Device Token: \(deviceTokenString)")
// Send this device token to your server
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for push notifications: \(error.localizedDescription)")
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// Handle push notifications in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound, .badge])
}
// Handle when the user taps on a notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("User tapped on the notification: \(response.notification.request.content.body)")
completionHandler()
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Push Notifications Example")
.font(.title).padding()
Text("Push notifications will appear here when sent from the server.")
.padding()
// Button for testing or interacting with notifications
Button("Send Test Push Notification") {
// Trigger server-side action to send a push notification
}.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}