While creating localnotification set the identifier in the notification which can be used for identifying the difference in the handling notification
Following is example creating localnotification with identifier.
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
Handling local notification with identifier.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "TestIdentifier" {
print("handling notifications with the TestIdentifier Identifier")
}
completionHandler()
}
For Handling remote notification you can use the following line
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("handling notification")
if let notification = response.notification.request.content.userInfo as? [String:AnyObject] {
let message = parseRemoteNotification(notification: notification)
print(message as Any)
}
completionHandler()
}
private func parseRemoteNotification(notification:[String:AnyObject]) -> String? {
if let aps = notification["aps"] as? [String:AnyObject] {
let alert = aps["alert"] as? String
return alert
}
return nil
}
You can add an additional condition for handling both the notification in the same method by checking identifier in the first
line.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("handling notification")
if response.notification.request.identifier == "TestIdentifier" {
print("handling notifications with the TestIdentifier Identifier")
}else {
if let notification = response.notification.request.content.userInfo as? [String:AnyObject] {
let message = parseRemoteNotification(notification: notification)
print(message as Any)
}
}
completionHandler()
}
private func parseRemoteNotification(notification:[String:AnyObject]) -> String? {
if let aps = notification["aps"] as? [String:AnyObject] {
let alert = aps["alert"] as? String
return alert
}
return nil
}