Search code examples
iosswiftios8uilocalnotification

Is there anyway to fire a UILocalNotification at a time user choose everyday in Swift?


I am building an app that needs to show a notification every day at the time the user set via UIDatePicker.

My code is from here:

@IBOutlet var myDatePicker: UIDatePicker!
@IBOutlet var mySwitch: UISwitch!

var localNotification = UILocalNotification()   // You just need one
var notificationsCounter = 0

// put your functions now
func datePicker()            { myDatePicker.datePickerMode = UIDatePickerMode.Time }
func notificationsOptions()  {
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = .CalendarUnitDay
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    localNotification.alertAction = "Open App"
    localNotification.alertBody = "Here is the seven o'clock notification"
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    //     you may add arbitrary key-value pairs to this dictionary.
    //     However, the keys and values must be valid property-list types
    //     if any are not, an exception is raised.
    // localNotification.userInfo = [NSObject : AnyObject]?
}
func toggleSwitch(){
    if mySwitch.on{
        localNotification.fireDate = myDatePicker.date
    } else {
        localNotification.fireDate = NSDate(timeIntervalSinceNow: 999999999999)   // will never be fired
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    datePicker()
    notificationsOptions()
    // Do any additional setup after loading the view, typically from a nib.
}

// here is where you place your IBActions

@IBAction func switchPressed(sender: AnyObject) {
    toggleSwitch()
}

But it doesn't work.


Solution

  • Solved by myself. I have accidentally set dateFormatter.dateFormat = "HH:mm:ss" wrong.