Show Local Notification in Swift IOS

In this article, we will learn how to show local Notification in Swift IOS. Local Notifications are simple and can add more value to your application.

Show Local Notification in Swift IOS -  Handy Opinion

Ask For Notification Permission from User

The UNUserNotificationCenter manages the activities relate to the notification. To use the notification the user needs to be asked for permission with the request authorization method.

Permission code is below.

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
    if success {
        print("Permission granted")
    } else if let error = error {
        print(error.localizedDescription) // problem occured, prints error message
    }
}

Create and Schedule Notification

Create and schedule notifications from your App when you wish to grab the user’s attention. You can show the notification immediately on the screen and you can set the time interval if want to change it.

Fill in the properties of the UNMutableNotificationContent object with the details of your message. The field determines how the notification is sent.

func showNotification(title: String, body: String) {
        
        let content = UNMutableNotificationContent()
        content.title = title
        content.subtitle = body
        content.sound = UNNotificationSound.default()        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false) // show notification immediately, you can set the time interval, if want to change
        // choose a random identifier
        let request = UNNotificationRequest(identifier: "any_identifier", content: content, trigger: trigger)
        // add our notification request
        UNUserNotificationCenter.current().add(request)
                
    }

How to Call this method

Below code shows how to call the showNotification() method.

showNotification(title: "Test Title", body: "body of notification")

In this tutorial, we have learn how to show local Notification in Swift IOS.

If you have any questions or suggestions, feel free to ask in the comments section below.

Next Article

1. How to Use DiffableDataSource with UI TableView in Swift IOS
2. UITextField for Emoji Input and Unchangeable Keyboard Type in Swift IOS
3. Get Device Identifier (UUID) and save in Keychain in Swift IOS
4. Find Distance between two locations in JAVA & SWIFT

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: