ios - UILocalNotification 多次触发 swift

标签 ios swift notifications nsdate uilocalnotification

所以,我试图制作一个每个实例多次触发的 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/

相关文章:

ios - XCode 12 : No persisted cache on this platform

ios - UILabel 新文本值未在 XCUITest 内更新

ios - Realm 文件大小因保存相同数据而异

ios - Swift3 Collection View 'attempt to delete item 1 from section 1, but there are only 1 sections before the update'

ios - 绘制连接的三角形条 (ios 6) 时出现倒三角条(缠绕问题)

iphone - 如何在 iphone 中使用圆角标签,UILabel Round Corners

ios - 如何让 CollectionView 仅在下半部分加载图像,同时仍允许在顶部加载静态内容

ios - 如果您在事先同意通知后禁用通知,Apple 如何处理推送 token ?

java - 如何在通知点击时返回应用程序

javascript - 在 php 和 jquery 上发出通知