A ‘local notification’ is a short text-based message which appears on the top of the screen. It lets users know that there is some information for them.
one can send and receive notification from two type
‘Push Notification’ => It is sent through the internet
‘Local Notification’ =>It is the schedule and sends locally in the iPhone
In this blog, we will learn about the local Notification. Before our application can send any notifications, we must fulfill the request for sending notifications so that the user can approve or reject it.
For successfully sending the local Notification we have to follow the following steps:-
Steps 1=> First We have to import UserNotifications in Appdelegates, and then we have to create a new 'notificationCenter'
property and have to assign an instance of the ‘UNUserNotificationCenter'
class to it to manage notifications. This will be our notification center.
For more information about ‘UNUserNotificationCenter’ you can check apple developer link https://developer.apple.com/documentation/usernotifications/unusernotificationcenter
1 |
let notificationCenter = UNUserNotificationCenter.current() |
Steps 2=> In the ‘didFinishLaunchingWithOptions‘ methods we will declare option for our notification, we will use the ‘badge‘, ‘sound‘, and ‘alert‘
1 |
let options: UNAuthorizationOptions = [.alert, .sound, .badge] |
Before sending the notification we have to ask permission from the user
1 2 3 4 5 6 |
notificationCenter.requestAuthorization(options: options) { (didAllow, error) in if !didAllow { print("Access denied") } } |
It will look like this when app launch
Step 3= > Now to trigger the ‘Notification’ we will create a method and call it when we like to call, like on any button click
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
func triggerNotification(){ let content = UNMutableNotificationContent() content.title = "Notification Title" content.subtitle = "Notification Subtitle" content.body = "Notification Body" content.userInfo = ["customData": "test data"] content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 4, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } |
We have set the time interval of 4 seconds. So, after 4 seconds the notification will show when the apps in the background
So please follow the above step to integrate Local Notification, and if you have any issue or suggestion you can leave your query/suggestion in the comment section.
Be the first to comment.