I've been all over these forums and other sites and I keep getting pieces of an answer that don't add up. Essentially, I would like to create a notification that fires, for example, every weekday at 6:28 AM, 12:28 PM, and 5:28 PM.
I have pieces of a solution, but I'm really unsure where to go. Am I setting this up right at all? Any help is appreciated.
let notification: UILocalNotification = UILocalNotification()
notification.category = "News and Sports"
notification.alertAction = "get caught up with the world"
notification.alertBody = "LIVE news and sports on VIC in just a minute!"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Preparing to show local notifications requires 2 main steps:
On iOS 8+ your app must ask and, subsequently, be granted permission by the user to display local notifications. Asking permission can be done as follows in your AppDelegate.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
if #available(iOS 8, *) {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
}
return true
}
Do not call registerUserNotificationSettings(_:)
when your app is running on a pre-iOS 8 operating system. Otherwise, your app will crash at runtime. Luckily, this shouldn't be a problem since you're working with Swift 2.
Schedule your notification at a future fireDate
.
let notification:UILocalNotification = UILocalNotification()
...
... // set the notification's category, alertAction, alertBody, etc.
...
notification.fireDate = ... // set to a future date
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Unfortunately, according to this Stack Overflow answer by @progrmr,
You cannot set custom repeat intervals with UILocalNotification. This has been asked before (see below) but only limited options are provided. The repeatInterval parameter is an enum type and it limited to specific values.
You cannot multiply those enumerations and get multiples of those intervals. You cannot have more than 64 local notifications set in your app. You cannot reschedule a notification once it fires unless the user chooses to run your app when the notification fires (they may not run it).
There is a request for repeat interval multipliers posted here. You can add comments to it. I suggest filing a bug report or feature request (url?) with Apple.
Many other Stack Overflow answers confirm the claims in the quotes above. Visit the link to the full quoted answer, which contains a list of supporting answers.
A potential workaround for your case would be to schedule 3 local notifications. Set each one to fire at 6:28 AM, 12:28 PM, and 5:28 PM, respectively. Then, set the repeatInterval
of all 3 local notifications to .CalendarUnitWeekday
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With