Local Notification in IOS 11 and swift 4? - ios

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))")
}
}
}

Related

iOS push notifications enabled but not working

I am trying to set push notifications in my app.
I have enabled my APN certificates..
And I have turned push notifications on in Xcode..
I have turned push notifications on in previous xcode projects and it worked fine. This is the code I have..
//add push notifications every 5 hours
func pushNotifications() {
let pushNotification = UNMutableNotificationContent()
pushNotification.title = "Time to track your water useage!"
pushNotification.badge = 1
let minute:TimeInterval = 60.0
let hour:TimeInterval = 60.0 * minute
let eighthDay:TimeInterval = 5 * hour
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: eighthDay, repeats: true)
let request = UNNotificationRequest(identifier: "timerDone", content: pushNotification, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
I am calling this in my viewdidload func
What am I doing wrong?
You can try this code,
func sendLocalPush() {
let objNotificationContent = UNMutableNotificationContent()
objNotificationContent.title = "Manish Kumar"
objNotificationContent.body = "iOS Developer"
objNotificationContent.userInfo = getUserInfoDict()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.0, repeats: false)
let request = UNNotificationRequest(identifier: "LocalNotification", content: objNotificationContent, trigger: trigger)
/// 3. schedule localNotification
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: {(_ error: Error?) -> Void in
})
}
Hope this helps.

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))")
}
})

UILocalNotification are showing only on lock screen/Notification screen

Whenever app receive silent push , I am displaying the local notification.
If at the time of receiving the silent push , iPhone is locked , local notification are displaying but if application is in background and iPhone is not locked then local notification are not displaying. What could be wrong. ? I am using below code ?
let content = UNMutableNotificationContent()
content.title = "Connect"
content.body = indentificationText
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
repeats: false)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
UNUserNotificationCenter.current().delegate = appDelegate
content.userInfo = payload.dictionaryPayload
let request = UNNotificationRequest(identifier: content.title, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
NSLog("UNUserNotificationCenter Add completion Handler : \(String(describing: error?.localizedDescription))")
})
The app may be suspended in the background , so the code that creates the local notification isn't executed . . .

Swift: Local Notifications not popping up, although request / scheduled seems to works - no errors

I am trying to learn how to use local notifications and currently I am just trying to let a notification pop up when a certain time has passed (for the sake of learning just 5 seconds).
I register the notification in this function, which is used at the end of an onBoarding screen:
func registerNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Granted.")
} else {
print("Not granted.")
}
}
}
Now to test the notification I just add the function set() to a button:
set() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Test Notification"
content.body = "It works!"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
But when the button is pressed and 5 seconds passed, no notification is shown, but also no error in Xcode, so I suppose this should all work?
What am I missing here? As far as I understand from various sources on the net this is the easiest way to display a local notification?
So to register a UserNotification and call the function at an appropriate
place:
func registerNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Granted.")
} else {
print("Not granted.")
}
}
}
This functions sets a notification with a time interval of 5 seconds. When the app is closed the notification will be displayed:
set() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Test Notification"
content.body = "It works!"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}

Two different Categories of local Notifications

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

Resources