斯威夫特 - 使用定时器/系统时钟/后台线程做一些事情每隔一小时我的应用程序(Swift - usi

2019-10-21 14:29发布

我正在使用:

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

为了得到一个通知,将自当前时间触发一个小时,问题是我想第一个完成后应用自动设置其他报警。 的NSTimer似乎并不像一旦应用进入它杀死定时器背景会因为工作。 我能做些什么来实现这一目标? 我可以捎带另一种方法到NSUserNotification

编辑:它也需要是动态的,我不能只设置通知的重复变量,因为我需要能够走多远切换出报警每次重置时间就越长。

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


文章来源: Swift - using timers/system clock/background threads to do something in my application every hour