Ryan.H
Ryan.H

Reputation: 361

Get a UILocalNotification to fire every week

I have set up a local notification to fire. I am wondering how to get it to repeat every week at the same time e.g., 9 AM on Monday.

Here's my code so far:

 @IBAction func scheduleLocal(sender: UIButton) {
guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() else { return
}
if settings.types == .None {
    let ac = UIAlertController(title: "Cant Schedule", message: "No Permission", preferredStyle: .Alert)
    ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    presentViewController(ac, animated: true, completion: nil)
    return
}
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.alertBody = "Come Exercise"
notification.alertAction = "Exercise Time"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["customField1": "w00t"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

and in viewDidLoad:

 let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) 

Upvotes: 1

Views: 2309

Answers (2)

zfetters
zfetters

Reputation: 457

There is a repeatInterval you can set on the local notification that takes an NSCalendarUnit as its type. You can read more about the different available calendar units here https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/#//apple_ref/c/tdef/NSCalendarUnit

You would likely be looking for NSCalendarUnitWeekOfYear

So you could just add the following to your code for your notification

notification.repeatInterval = NSCalendarUnit.WeekOfYear

Upvotes: 2

Juan de Dios
Juan de Dios

Reputation: 2789

Your code is right.

But: "Each app on a device is limited to 64 scheduled local notifications." https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/WhatAreRemoteNotif.html

You can schedule the local notifications and recreate them each time the user open the app. Or use remote notifications instead.

Upvotes: 0

Related Questions