Find List of Local Notification the App Has Already Set

Find list of Local Notification the app has already set

UIApplication has a property called scheduledLocalNotifications which returns an optional array containing elements of type UILocalNotification.

UIApplication.shared.scheduledLocalNotifications

How to get the local notifications which are listed in Notifications pull down?

Not at all. There is no api to get that. sorry

-- you can see notifications that are pending (not yet delivered to the user) only

Limiting local notifications set at the same to one

This is the normal and intended behaviour. Two notifications might have the same time but completely different data, so they are not restricted to one per unit time.

I would set the unique identifier of the notification and keep track of them in an array.

Here is an example:

let center = UNUserNotificationCenter.current()

// Setup content

let content = UNMutableNotificationContent()

content.title = "Notificaion title"

content.body = "Yoir text here"

content.sound = UNNotificationSound.default()

content.categoryIdentifier = "YouCanHaveDifferentCategories"

content.userInfo = ["myKey": "myValue"]

// Setup trigger time

var calendar = Calendar.current

let now = Date()

let date = calendar.date(byAdding: .second, value: 10, to: now)

let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)

// Create request

// Set any unique ID here. I use the UUID tools. This value is used by notificaion center, but I alsp store it in an array property of the relevant object in my data model, so the notification can be removed if the user deletes that object.
let uniqueID = UUID().uuidString

let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)

// Add the notification request
center.add(request)

You can then selectively delete notifications with these methods, as long as you have a record in an array or your data model of the identifiers. You can pass an array to delete multiple at once.

center.removePendingNotificationRequests(withIdentifiers: "UniqueID")

center.removeDeliveredNotifications(withIdentifiers: "UniqueID")

Getting local notifications to show while app is in foreground Swift 3

There is a delegate method to display the notification when the app is open in iOS 10. You have to implement this in order to get the rich notifications working when the app is open.

extension ViewController: UNUserNotificationCenterDelegate {

//for displaying notification when app is in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

//If you don't want to show notification when app is open, do something here else and make a return here.
//Even you you don't implement this delegate method, you will not see the notification on the specified controller. So, you have to implement this delegate and make sure the below line execute. i.e. completionHandler.

completionHandler([.alert, .badge, .sound])
}

// For handling tap and user actions
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

switch response.actionIdentifier {
case "action1":
print("Action First Tapped")
case "action2":
print("Action Second Tapped")
default:
break
}
completionHandler()
}

}

In order to schedule a notification in iOS 10 and providing a badge

override func viewDidLoad() {
super.viewDidLoad()

// set UNUserNotificationCenter delegate to self
UNUserNotificationCenter.current().delegate = self
scheduleNotifications()
}

func scheduleNotifications() {

let content = UNMutableNotificationContent()
let requestIdentifier = "rajanNotification"

content.badge = 1
content.title = "This is a rich notification"
content.subtitle = "Hello there, I am Rajan Maheshwari"
content.body = "Hello body"
content.categoryIdentifier = "actionCategory"
content.sound = UNNotificationSound.default

// If you want to attach any image to show in local notification
let url = Bundle.main.url(forResource: "notificationImage", withExtension: ".jpg")
do {
let attachment = try? UNNotificationAttachment(identifier: requestIdentifier, url: url!, options: nil)
content.attachments = [attachment!]
}

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 3.0, repeats: false)

let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error:Error?) in

if error != nil {
print(error?.localizedDescription ?? "some unknown error")
}
print("Notification Register Success")
}
}

In order to register in AppDelegate we have to write this piece of code in didFinishLaunchingWithOptions

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForRichNotifications()
return true
}

I have defined actions also here. You may skip them

func registerForRichNotifications() {

UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { (granted:Bool, error:Error?) in
if error != nil {
print(error?.localizedDescription)
}
if granted {
print("Permission granted")
} else {
print("Permission not granted")
}
}

//actions defination
let action1 = UNNotificationAction(identifier: "action1", title: "Action First", options: [.foreground])
let action2 = UNNotificationAction(identifier: "action2", title: "Action Second", options: [.foreground])

let category = UNNotificationCategory(identifier: "actionCategory", actions: [action1,action2], intentIdentifiers: [], options: [])

UNUserNotificationCenter.current().setNotificationCategories([category])

}

If you want that your notification banner should be shown everywhere in the entire application, then you can write the delegate of UNUserNotificationDelegate in AppDelegate and make the UNUserNotificationCenter current delegate to AppDelegate

extension AppDelegate: UNUserNotificationCenterDelegate {

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response.notification.request.content.userInfo)
completionHandler()
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}

Check this link for more details

https://www.youtube.com/watch?v=Svul_gCtzck

Github Sample

https://github.com/kenechilearnscode/UserNotificationsTutorial

Here is the output

Sample Image

Sample Image

Scheduling local notifications in swift

When you store something to UserDefaults, it stays even after the app closes. That's why the notification doesn't show again.

If you don't want it to be persisted across app launches, you should set it to false at the app launch time (I assume that's what you mean by refreshed):

You can add this to your UIApplicationDelegate (or add the line to existing didFinishLaunchingWithOptions):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// this clears the flag
UserDefaults.standard.setValue(false, forKey: "userHasBeenNotified")
return true
}

Or, if you have a way of sharing state throughout the app (singleton perhaps), you can avoid UserDefaults and save it as a member of whatever class you use.

Swift: Local Notifications get scheduled 1h earlier

This is related to daylight saving and because it is changing on the 31/03/2019. Also if you put a breakpoint and check the contents of the triggerDates array you will see what the dates actually look like and it is only the printing to the console that is causing your issue.

If you add 1 days in BST on the 30/03/2019 you are in fact only adding 23 hours in UTC because of daylight saving time. However if you convert it back it will be ok.



Related Topics



Leave a reply



Submit