Two different Categories of local Notifications - ios

I created two different functions that each create a new local notification.
func scheduleLocalNotification() {
// Create Notification Content
let notificationContent = UNMutableNotificationContent()
// Configure Notification Content
notificationContent.title = "Notif 1"
notificationContent.subtitle = "Local Notifications"
notificationContent.body = "hellow worlds."
// Set Category Identifier
notificationContent.categoryIdentifier = Notification.Category.tutorial
// Add Trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
func scheduleLocalNotification2() {
// Create Notification Content
let notificationContent = UNMutableNotificationContent()
// Configure Notification Content
notificationContent.title = "Notif 2"
notificationContent.subtitle = "Local Notifications"
notificationContent.body = "hellow world + snooze"
// Set Category Identifier
notificationContent.categoryIdentifier = Notification.Category.tutorial
// Add Trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
I want the first function to create a normal notification without any actions and the second to create a notification with action button. So I create the following function
func configureUserNotificationsCenter() {
// Configure User Notification Center
UNUserNotificationCenter.current().delegate = self
// Define Actions
let actionReadLater = UNNotificationAction(identifier: Notification.Action.readLater, title: "Read Later", options: [])
let actionShowDetails = UNNotificationAction(identifier: Notification.Action.showDetails, title: "Show Details", options: [.foreground])
let actionUnsubscribe = UNNotificationAction(identifier: Notification.Action.unsubscribe, title: "Unsubscribe", options: [.destructive, .authenticationRequired])
// Define Category
let tutorialCategory = UNNotificationCategory(identifier: Notification.Category.tutorial, actions: [actionReadLater, actionShowDetails, actionUnsubscribe], intentIdentifiers: [], options: [])
// Register Category
UNUserNotificationCenter.current().setNotificationCategories([tutorialCategory])
}
I then call the configureUserNotificationsCenter in viewdidload but this causes all my notifications to have these action buttons. I want only the notifications scheduled using the scheduleLocalNotifications2 function and the notifications with other functions should not have these action buttons. How do I go around making that?

Both methods are using a notificationContent.categoryIdentifier of Notification.Category.tutorial. This is the same category that you are specifying the buttons on, which is why it shows up for both. You need to create a second category identifier for your notification with no buttons

Related

iOS 13 UNNotificationAction button not showing

Actions fail to show.
And, they also fail to show with these downloaded notification demo apps
- LocalNotifications by Bart Jacobs
- RemindMe by Keith Harrison (Use Your Loaf)
- EatMoreVegetable by Brian Advent
Interestingly, I can make action button appear by doing this:
Step
1) In app, fire notification request
2) Leave app - go to Home screen
3) Notification appears without action button
4) Drag notification down causes action button to appear
Same results with simulator or device.
My demo app can be downloaded from here
https://github.com/tricarb/UNLocalDemo
func registerCategories() {
let center = UNUserNotificationCenter.current()
let actionID = Notify.actionID.rawValue
let categoryID = Notify.categoryId.rawValue
let action = UNNotificationAction(identifier: actionID, title: "Action Title", options: [.foreground])
let category = UNNotificationCategory(identifier: categoryID, actions: [action], intentIdentifiers: [])
center.setNotificationCategories([category])
}
func fireNotification() {
let content = UNMutableNotificationContent()
content.title = "Content Title"
content.body = "This is the content body"
content.categoryIdentifier = Notify.categoryId.rawValue
let timeInterval = TimeInterval(7)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
if let error = error {
print(error.localizedDescription)
} else {
print("Notification will fire in", timeInterval, "seconds")
}
}
}
To get action button to show you need to swipe the notification to the left (in notification center). There you'll see three buttons: "Manage", "View", "Clear".
Select "View" and you'll get the same behavior as you have when you drag down the notification that just appeared.

Receiving notifications from default notification center while app in background

In my app, I'm fetching the content of camera-roll with fetchAssets(with:). To receive change messages, I've registered my observer with the photo library’s register(_:) method. My observer is comforting to the PHPhotoLibraryChangeObserver protocol. So when the library is changing, I should get notified about that. The scenario I want to support is while I'm running my app, I go to background, then open the camera app, take a picture, then go back to my app. Is it possible to get the notification of a change that occurred while my app was in background, when it comes back to foreground?
Yes you can create LocalNotificaion and trigger it when app is going in background and coming back in foreground.
func scheduleNotification(timeInter : TimeInterval) {
let content = UNMutableNotificationContent()
let userActions = "User Actions"
content.title = "Title "
content.body = "Body"
content.sound = UNNotificationSound.init(named:
content.categoryIdentifier = userActions
content.userInfo = ["MID" : RANDOM_ID, "timeInterval" : String(timeInter)]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInter, repeats: false)
let identifier = String(timeInter)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
print(request.identifier)
notificationCenter.add(request) { (error) in
if let error = error {
}
}
// let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "Delete", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: userActions, actions: [deleteAction], intentIdentifiers: [], options: [])
notificationCenter.setNotificationCategories([category])
}

Rich local notification

How can we show the image or any attachment with local notifications as we used to show in rich notifications ?
I am receiving the silent notification and then changing it in local notification.
Yes, you can show it in the local notification also, you have to trigger local notification after you received silent push , I hope in your slient notification payload all require data is there.
Here is the code snippet
let content = UNMutableNotificationContent()
//Configure notification
content.title = "Notification Title"
content.body = "Notification Body"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "ImageNotification"
//Attach your image local path here (Document dir path)
let attachment = try! UNNotificationAttachment(identifier: "\(NSDate().timeIntervalSince1970 * 1000)", url: localURL, options: [:])
content.attachments = [attachment]
content.userInfo = ["attachmentType": "Media"]
// Create a trigger for fire a local notification
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)
let request = UNNotificationRequest(identifier: "\(NSDate().timeIntervalSince1970 * 1000)", content: content, trigger: trigger)
// Configure according to version
if #available(iOS 11.0, *) {
let contactCategory = UNNotificationCategory(identifier: content.categoryIdentifier,
actions: [],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "",
options: .customDismissAction)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([contactCategory])
} else {
// Fallback on earlier versions
let contactCategory = UNNotificationCategory(identifier: content.categoryIdentifier, actions: [], intentIdentifiers: [], options: [])
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([contactCategory])
}
UNUserNotificationCenter.current().add(request) {[weak self] (error) in
guard error == nil else {
return
}
}
After this implement it would be work fine, If you still facing any issue so please let me know.

How to show multiple local notifications?

I have an messaging app,I am using VoIP notifications to send acknowledgement to users. I am firing a local notification each time the PushKit delegate is called.
The current scenario is that the previous notification gets removed and is replaced by a newer one. Is there a way to manage local notifications such that the user can see multiple notifications in their device?
This is the code I have tried:
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Title"
notificationContent.subtitle = "Subtitle"
notificationContent.body = "Body"
// Add Trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
P.S : I don't want to schedule local notification for a later period
Using for loop to register multiple Notification with the unique identifier https://developer.apple.com/documentation/usernotifications/unnotificationrequest/1649634-identifier?language=objc
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
you should change this identifier "cocoacasts_local_notification" to dynamically reset the unique identifier
let notification = UNMutableNotificationContent()
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dayComponent, repeats: true)
let lnMessageId:String = messageDict["Id"] as! String
let dayRequest = UNNotificationRequest(identifier: lnMessageId , content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(dayRequest, withCompletionHandler: {(_ error: Error?) -> Void in
if error == nil
{
//print("success")
}
else
{
//print("UNUserNotificationCenter Error : \(String(describing: error?.localizedDescription))")
}
})

Local Notification in IOS 11 and swift 4?

My app works perfectly on ios 10 but on ios 11 it does not push local Notification.
Is there any error in my code?
let notificationContent = UNMutableNotificationContent()
let sound = self.defaults.string(forKey: "azan")!
// Configure Notification Content
notificationContent.title = "کاتەکانی بانگ"
notificationContent.sound = UNNotificationSound(named: sound)
//notificationContent.subtitle = self.notificationstring
notificationContent.body = self.notificationstring
// Add Trigger
if(TimeInterval(time) > 0)
{
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(time), repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}

Resources