NSLocalNotification的重复.驳回.合适的方式

thi*_*ift 0 notifications ios swift

我想在上午10点创建每日通知,每天都有不同的内容.

func createNotification() {

let dateComp:NSDateComponents = NSDateComponents()
dateComp.hour = 10; // supposed to run each day at 10AM

var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date:NSDate = myCalendar.dateFromComponents(dateComp)!

let localNotification = UILocalNotification()
localNotification.fireDate = date
localNotification.alertBody = getContentStringForNotification() // Method returns different string for each date
localNotification.repeatInterval = .Day // Repeats every day
localNotification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

}
Run Code Online (Sandbox Code Playgroud)

它重复通知.他们不断重复并返回昨天的通知.我搜索了Stack社区的问题,我没有找到解雇它们的正确方法.

我认为:

  • 应用程序已终止,它们已安排并独立于应用程序执行操作.反复运行应用程序将创建更多通知.
  • 通知没有被正确解雇,并且即使在第二天也会返回昨天的消息.

帮助:

  1. 什么是解雇他们或检查他们是否已被解雇的正确方法(确保他们不重复
  2. 我是否每天都会循环并创建所有年份的通知,或者每次运行应用程序时为明天创建一个新通知

我错过了什么?代码欢迎.谢谢!

小智 6

localNotification.repeatInterval = .Day // Repeats every day
Run Code Online (Sandbox Code Playgroud)

这使得通知会自动为每天安排,因此如果要显示相同的通知(时间和内容),则不应安排新通知.

如果要重新安排通知,请首先清除计划中的所有先前本地通知,或阅读有关如何清除单个UILocalNotification的文档

UIApplication.sharedApplication().cancelAllLocalNotifications()
Run Code Online (Sandbox Code Playgroud)