gpt4 book ai didi

ios - UILocalNotification 多次触发 swift

转载 作者:行者123 更新时间:2023-11-30 14:04:17 25 4
gpt4 key购买 nike

所以,我试图制作一个每个实例多次触发的 UILocalNotification。也就是说,用户选择迭代间隔(即每 2 小时),并使用 DateTimePicker 选择通知停止的日期(即 2015 年 11 月 1 日)。我寻找了几个答案,每个答案中总是缺少一个解决方案,而且由于我对 iOS 开发相对较新,我不知道如何正确实现它们。大多数问题是迭代值和结束日期正确触发。有人可以帮忙吗?

最佳答案

您需要使用类似 NSTimer 的东西来安排重复任务,如下所示(时间以秒为单位):

var interval = 60.0 // user chosen interval
var helloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: Selector("helloWorld"), userInfo: nil, repeats: true)

func helloWorld()
{
println("Hello, World!")
}

然后,您还需要设置另一个类似于上面的计时器来检查日期(在本示例中,它每小时执行一次,但您可以通过更改间隔来提高/降低准确性)。一旦日期匹配,您就可以使之前的计时器失效以停止重复:

let chosenDate = "01.11.2015" // example date chosen with your DateTimePicker
var dateTimer = NSTimer.scheduledTimerWithTimeInterval(60.0 * 60, target: self, selector: Selector("checkDate"), userInfo: nil, repeats: true)

func checkDate() {
let date = NSDate()
println(date)
let formatter = NSDateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let formattedDate = formatter.stringFromDate(date)

if formattedDate == chosenDate {
helloWorldTimer.invalidate() // disable previous timer
dateTimer.invalidate() // must also stop this timer as attempting to invalidate the other once already stopped would cause a crash
}
}

n.b.确保您的日期采用相同的格式进行比较

n.b.2.这是使用 Swift 1.2 编写的

关于ios - UILocalNotification 多次触发 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32605663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com