Swift-使用计时器/系统时钟/后台线程每小时在我的应用程序中执行一些操作 [英] Swift - using timers/system clock/background threads to do something in my application every hour

查看:75
本文介绍了Swift-使用计时器/系统时钟/后台线程每小时在我的应用程序中执行一些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用:

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

要获取从当前时间开始一个小时发出的通知,问题是我希望该应用在第一个警报结束后自动设置另一个警报.NSTimer似乎无法正常工作,因为一旦应用程序进入后台,它将杀死计时器.我该怎么做呢?我可以将另一种方法带回到NSUserNotification

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

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

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.

推荐答案

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

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)

这篇关于Swift-使用计时器/系统时钟/后台线程每小时在我的应用程序中执行一些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆