Swift - using timers/system clock/background threads to do something in my application every hour

坚强是说给别人听的谎言 提交于 2019-12-24 17:43:26

问题


I'm using:

var alarm = NSUserNotification()
var currentTime = NSDate()
alarmTime = currentTime.dateByAddingTimeInterval(60)
alarm.deliveryDate = alarmTime
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(alarm)

To get a notification that will fire an hour from the current time, the problem is I want the app to automatically set up another alarm after the first one finishes. NSTimer doesn't seem like it will work because once the app goes to the background it kills the timer. What can I do to achieve this? Can I piggy back another method onto a NSUserNotification

Edit: it also needs to be dynamic, I can't just set the repeat variable of the notification because I need to be able to switch how far out the alarm will be each time it resets.


回答1:


You just have to set your deliveryRepeatInterval and deliveryTimeZone, as follow:

// set your deliveryTimeZone to localTimeZone
alarm.deliveryTimeZone = NSTimeZone.localTimeZone()

// The date components that specify how a notification is to be repeated.
// This value may be nil if the notification should not repeat.
// alarm.deliveryRepeatInterval = nil

// The date component values are relative to the date the notification was delivered.
// If the calendar value of the deliveryRepeatInterval is nil
// the current calendar will be used to calculate the repeat interval.
// alarm.deliveryRepeatInterval?.calendar = NSCalendar.currentCalendar()

// to repeat every day, set .deliveryRepeatInterval.day to 1.
alarm.deliveryRepeatInterval?.day = 1
// to repeat every hour, set .deliveryRepeatInterval.hour to 1.
alarm.deliveryRepeatInterval?.hour = 1

 alarm.deliveryDate = NSDate().dateByAddingTimeInterval(60)

NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(alarm)


来源:https://stackoverflow.com/questions/27915137/swift-using-timers-system-clock-background-threads-to-do-something-in-my-appli

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