Question on how to proceed with UNUserNotificationCenter 64 limit - ios

I am trying to make a reminder app and all my notification repeat is set to true
Example :
var dateComponents = DateComponents()
dateComponents.weekday = 1
dateComponents.hour = Int(hour)
dateComponents.minute = Int(minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let requestIdentifier = "\(timeArrayToSaveInMobile[indexTime].alarmId!)Sunday"
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
I've browse around here and some people mentioned that the system keeps the soonest-firing 64 notifications.
So, if I have already reached the limit but I set another notification that will fire earlier than some of the notification in the (64 list) it should replace one of the notification right? Since it will fire earlier that some of the pre-set notification in the list.
My problem is similar to this ios 10 swift 3 add more than 64 local notifications does not keep soonest

Notifications will reset when you open the app, thus you can set/send another 64 after every time you close the application.
The system discards scheduled notifications in excess of this limit, keeping only the 64 notifications that will fire the soonest. Recurring notifications are treated as a single notification.
in your example you have set one notification for Sunday which is only count one for each Sunday.

Related

getPendingNotificationRequests count is not decreasing on notification firing if UNCalendarNotificationTrigger repeat set to true

I am working on a app in that i need to schedule more than 64 notification at a time so i am schedule 64 notifications first and storing rest in database.
All notification is scheduling with UNCalendarNotificationTrigger repeat "true", because that will repeat every day/week.
So problem is that count of pendingNotificationRequest doesn't decrease of notification fires.
if i schedule 60 notifications and 10 notification fires at scheduled time, still i get 60 pending notification request from below code.
if i set to trigger repeat false it works fine, Please assist how can it work in repeat true.
let center1 = UNUserNotificationCenter.current()
center1.getPendingNotificationRequests(completionHandler: { requests in
print("Total Count : \(requests.count)")
})

Running local notifications with hourly interval every day for specific amount of time

How can I make my app to be able to fire local notifications every day with customisable interval but only for allocated amount of time, for example: from 10:00 to 20:00pm?
Now I only implemented repeated notifications with custom interval:
func beginNotifications(_ config: UserConfig) {
let interval = config.notificationInterval
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
content.title = "Content title"
content.subtitle = "Content body"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)
let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)
center.add(request)
}
By far I only came up with solution - to make two separate methods using Timer, which will start and stop notification function daily, and enable Background Mode for the app.
The first solution came to my mind if scheduling the local push notification N-times (how many times as you want). You just need to make the identifier unique of course.
By far I only came up with solution - to make two separate methods
using Timer, which will start and stop notification function daily,
and enable Background Mode for the app.
This isn't recommended imo, and if you push this, you might need to deal with Apple review team.

Limiting local notifications set at the same to one

I've implemented a date picker for setting reminders which sends a local notification. During testing, I noticed I can set a reminder multiple times at the same time. I assumed the system would recognize I've already set it once at that particular time, and would not save another reminder. Surprisingly, the app sent more than once notification at the same time.
I figured I implemented this incorrectly so I decided to test the default Clock app. Again, I set two alarms at the same time, and I got two notifications concurrently:
Is this a normal behaviour for notifications? Are my assumptions wrong? Maybe this would've been okay when the user wanted to assign different messages to separate notifications. However, in my case, the app is supposed to remind users for one simple task, with a static message.
Is there a way to fix this "problem"? The way I see it, if I've already set a reminder, the app should still show that a new reminder has been saved, but not actually save the new 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")

Swift - Daily Local Notification with Event

In my application users will set a time. On that time I need to send them a daily notification with the count of newly created appointments. For example assume there are 3 appointments having on "01-03-2017". So on that day, at a selected time user should get a notification mentioning that "you have 3 new appointments". Newly added appointments will be saved in local realm db.
Actually what I have to do is every day user mentioned time, there should be run a code segment and check whether are there any new appointments in db. If so need to fire local notification. Even app is close this should work. I saw that in Android we can do this using alarm manager. But in swift I didn't found a way to do this.
I am not a expert in swift. So appreciate if you can give me a solution with a explanation. Thank you for your time.
You will not be able to run code at desired time, as iOS prevents from doing this.
Though, if the realm database is updated, it means the app is running at some point to add the new appointments.
When it occurs, you could have a function similar to the following to create a local notification
func createLocalNotification(atDate date: DateComponents, appointmentCount: Int) {
var content = UNMutableNotificationContent()
content.title "You have \(appointmentCount) appointment(s) today"
content.badge: appointmentCount
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
let notificationRequest = UNNotificationRequest(identifier: "notification-request-\(date.day!)-\(date.month!)-\(date.year!)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(notificationRequest)
}

Local Notification Not Firing

I'm trying to use local notification, this is my code:
appdelegate
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories: nil))
notificationViewController
let localNotification:UILocalNotification = UILocalNotification()
var BDate = friend.birthday.componentsSeparatedByString("/")
let date = NSDate.date(year: 2015, month: Int(BDate[1])!, day: Int(BDate[0])! - daysBefore, hour: hour, minute: min, second: 0)
localNotification.soundName = "notificationSound.mp3"
localNotification.alertBody = friend.fullName + " has a birthday today!"
localNotification.fireDate = date
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.Year
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
friend.birthday is a string - "DD/MM/YYYY"
I'm calling the setNotification function for every friend in a friends array. When there are only one or two friends I get the notification but one there are ~100+ I no longer get the notification.
I know the fireDate is correct, I checked it.
Why the code isn't working?
Each app on a device is limited to 64 scheduled local notifications. The system discards scheduled notifications in excess of this limit, keeping only the 64 notifications that will fire the soonest. Recurring notifications are treated as a single notification.
You can find more detail here
Looks like you're really exceeded the notifications limit. There's several tips and guidelines that might help:
Try to check your date versus NSDate() and schedule notification only if date.timeIntervalSinceReferenceDate > NSDate().timeIntervalSinceReferenceDate (There is a compare method in NSDate, but I prefer to compare raw values)
Scheduling local notifications one-by-one is very expensive for application performance, so you can form an array of notifications and schedule them all at once. Use UIApplication.sharedApplication().scheduledLocalNotifications property for that purpose.
This will allow you effectively reschedule all notifications on every application launch. For example in applicationDidFinishLaunching() delegate method.
And also, this will give you another advantage: you can easily check for notifications limit and, if necessary, add/replace 64-th notification with prompt to user to launch your app to allow it to schedule more notifications. This is a common practice for many applications to deal with Apple's limitations.

Resources