user3479083 user3479083 - 5 months ago 123
iOS Question

Repeating Local Notifications every Week with Swift

I have an app using local notifications there is a total of 64 notifications, which is the limit of local notifications. I need to repeat each notification every week. I know that to set the repeat interval you use:

alarm.repeatInterval = NSCalendarUnit


I have tried using the .WeekOfYear and .WeekOfMonth. Do they repeat the notification every year or month? And I do not know the calendar unit for weekly. Which one can I use to repeat weekly?

Edit:

This is the code I am using to set the notifications.

let notifyAlarm = UILocalNotification()
let component = NSDateComponents()
component.hour = NSUserDefaults.standardUserDefaults().integerForKey("Hour1")
component.minute = NSUserDefaults.standardUserDefaults().integerForKey("Minute1")
component.weekday = 1

notifyAlarm.fireDate = calendar.dateFromComponents(component)
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
notifyAlarm.alertBody = NSUserDefaults.standardUserDefaults().stringForKey("Message1")
notifyAlarm.repeatInterval = NSCalendarUnit.WeekdayOrdinal
notifyAlarm.soundName = NSUserDefaults.standardUserDefaults().stringForKey("Sound1")
app.scheduleLocalNotification(notifyAlarm)


I am setting 64 notifications like that at once. But with different dates.

Answer

If you want the notification to fire for first time after a week you need to change the fire date. I use TimeIntervalSinceNow for this, 1 week would be around 600000 seconds. Maybe a bit clunky but I think its the easiest for those type of notifications. You can use _ to separate numbers for legibility.

alarm.fireDate = NSDate(timeIntervalSinceNow: 600_000)

Repeat interval should be weekOfYear

alarm.repeatInterval = NSCalendarUnit.WeekOfYear

The first repeating notification should fire 1 week after the first (fireDate) notification fired.

For a full list have a look at this (thanks madmik3)

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/#//apple_ref/c/tdef/NSCalendarUnit