Search Your Question

Local Notification in iOS

Ans : 

Q.
 what the best way to Scheduled more than one notification but not remove the previous one?
A. Use different identifier

Different type of request access under UNAuthorizationOptions like .alert, .badge, .sound and .carplay.

let center =  UNUserNotificationCenter.current()a
center.requestAuthorization(options: [.alert, .sound, .badge]) { (result, error) in

 //handle result of request failure

}

UNNotificationRequest helps to create notification request. Which requires 3 information like an identifier, content and trigger.

1. identifier : It is unique for every notification. If we send another notification with same identifier it remove existing notification and replace it with new one.

2. content : display it in banner and main attributes are title, subtitle, body and attachment media. Using UNMutableNotificationContent we can define content.

3. trigger : the event that will trigger the notification to be displayed to the user. There are 3 classes as UNTimeIntervalNotificationTrigger,UNCalendarNotificationTrigger,UNLocationNotificationTrigger which are subclass of  UNNotificationTrigger.

example of creating local notification :

//get the notification center
let center =  UNUserNotificationCenter.current()

//create the content for the notification
let content = UNMutableNotificationContent()
content.title = " Jurassic Park"
content.subtitle = "Lunch"
content.body = "Its lunch time at the park, please join us for a dinosaur feeding"
content.sound = UNNotificationSound.default()

//notification trigger can be based on time, calendar or location
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:2.0, repeats: false)

//create request to display
let request = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: trigger)

//add request to notification center
center.add(request) { (error) in
    if error != nil {
        print("error \(String(describing: error))")
    }
}

-> UNUserNotificationCenterDelegate having 2 methods which is used to display notification when app is in foreground. (WillPresent delegate method is used for display notification when app in foreground).



No comments:

Post a Comment

Thanks