Swift notification fire from datePicker

心已入冬 提交于 2019-12-04 14:54:38

Try like this:

class ViewController: UIViewController {

    @IBOutlet var datePicker: UIDatePicker!
    @IBOutlet var notificationSwitch: UISwitch!

    let localNotification = UILocalNotification()

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNotificationsOptions()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func setUpNotificationsOptions()  {
        datePicker.datePickerMode = .Time
        localNotification.timeZone = NSTimeZone.localTimeZone()
        localNotification.repeatInterval = .Day
        localNotification.alertAction = "Open App"
        localNotification.alertBody = "a notification"
        localNotification.soundName = UILocalNotificationDefaultSoundName
    }

    func toggleNotification() {
        if notificationSwitch.on {
            localNotification.fireDate = datePicker.date.fireDate
            UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
        } else {
            localNotification.fireDate = nil
            UIApplication.sharedApplication().cancelLocalNotification(localNotification)
        }
    }
    @IBAction func toggleSwitch(sender: UISwitch) {
       toggleNotification()
    }
    @IBAction func dateChanged(sender: UIDatePicker) {
       toggleNotification()
    }
}

you will need those extensions:

extension NSDate {
    var minute: Int {
        return NSCalendar.currentCalendar().component(.Minute, fromDate: self)
    }
    var hour: Int {
        return NSCalendar.currentCalendar().component(.Hour, fromDate: self)
    }
    var day: Int {
        return NSCalendar.currentCalendar().component(.Day, fromDate: self)
    }
    var month: Int {
        return NSCalendar.currentCalendar().component(.Month, fromDate: self)
    }
    var year: Int {
        return NSCalendar.currentCalendar().component(.Year, fromDate: self)
    }
    var fireDate: NSDate {
        let today = NSDate()
        return NSCalendar.currentCalendar().dateWithEra(1,
            year: today.year,
            month: today.month,
            day: { hour > today.hour || (hour  == today.hour
               &&  minute > today.minute) ? today.day : today.day+1 }(),
            hour: hour,
            minute: minute,
            second: 0,
            nanosecond: 0
            )!
    }
}

It looks like the fireDate property is only being set inside the toggleSwitch() method. How is that method being reached? I would suggest you move the content of that method right into your notificationsOptions() method.

As an aside, you might want to consider slightly more useful names for your methods: datePicker() and notificationOptions() are likely to cause you maintenance headaches later on because they aren't very descriptive.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!