使用swift在设定的时间每天重复本地通知

JUS*_*DEV 14 cocoa-touch ios uilocalnotification swift

我是iOS开发的新手,但已经创建了应用程序,我正在尝试创建一段时间的每日通知.目前,通知对于给定的日期/时间执行一次.我不确定如何使用repeatInterval方法每天安排它.每天重复通知的最佳方法是什么?任何帮助将不胜感激(Y).

    var dateComp:NSDateComponents = NSDateComponents()
    dateComp.year = 2015;
    dateComp.month = 06;
    dateComp.day = 03;
    dateComp.hour = 12;
    dateComp.minute = 55;
    dateComp.timeZone = NSTimeZone.systemTimeZone()

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

    var notification:UILocalNotification = UILocalNotification()
    notification.category = "Daily Quote"
    notification.alertBody = quoteBook.randomQuote()
    notification.fireDate = date
    notification.repeatInterval = 

    UIApplication.sharedApplication().scheduleLocalNotification(notification)
Run Code Online (Sandbox Code Playgroud)

Viz*_*llx 14

您必须提供NSCalendarUnit值,如"HourCalendarUnit"或"DayCalendarUnit",以重复通知.

只需添加此代码即可每天重复本地通知:

notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
Run Code Online (Sandbox Code Playgroud)

  • 由于某种原因,通知一个接一个地被推送.我把它改为几分钟来测试,但从那时起,即使我把它改回来,通知仍然被推送.有什么想法吗?@vizllx (3认同)
  • 如果通过一个接一个地推送,我刚刚发现在不同安装会话中注册的本地通知仍然存在 - 如果您卸载然后重新安装应用程序,则先前的通知(如果尚未触发)将立即全部触发(如果是本地通知)在最新的安装会话中再次启用通知。希望这对其他人有帮助。 (2认同)

Kei*_*day 13

所以,不得不修改@ vizllx上面的代码.这是新行:

notification.repeatInterval = NSCalendarUnit.Day 
Run Code Online (Sandbox Code Playgroud)

这是我使用的完整工作示例:

let notification = UILocalNotification()

  /* Time and timezone settings */
  notification.fireDate = NSDate(timeIntervalSinceNow: 8.0)
  notification.repeatInterval = NSCalendarUnit.Day
  notification.timeZone = NSCalendar.currentCalendar().timeZone
  notification.alertBody = "A new item is downloaded."

  /* Action settings */
  notification.hasAction = true
  notification.alertAction = "View"

  /* Badge settings */
  notification.applicationIconBadgeNumber =
  UIApplication.sharedApplication().applicationIconBadgeNumber + 1
  /* Additional information, user info */
  notification.userInfo = [
    "Key 1" : "Value 1",
    "Key 2" : "Value 2"
  ]

  /* Schedule the notification */
  UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
Run Code Online (Sandbox Code Playgroud)