Swift - 使用计时器/系统时钟/后台线程每小时在我的应用程序中执行一些操作

时间:2015-01-13 04:57:18

标签: macos swift background nsdate nsusernotification

我正在使用:

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

要获得从当前时间开始一小时的通知,问题是我希望应用在第一个完成后自动设置另一个警报。 NSTimer似乎不会起作用,因为一旦应用程序进入后台它就会杀死计时器。我能做些什么来实现这个目标?我可以将另一种方法放回NSUserNotification

编辑:它也需要是动态的,我不能只设置通知的重复变量,因为我需要能够在每次重置时切换警报的距离。

1 个答案:

答案 0 :(得分:1)

您只需设置deliveryRepeatInterval和deliveryTimeZone,如下所示:

// 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)