Repeating local notification daily at a set time with swift

给你一囗甜甜゛ 提交于 2019-11-27 07:19:37

You have to provide an NSCalendarUnit value like “HourCalendarUnit” or “DayCalendarUnit” for repeating a notification.

Just add this code to repeat the local notification daily :

notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
Keith Holliday

So, had to modify the @vizllx's above code slighty. Here is the new line:

notification.repeatInterval = NSCalendarUnit.Day 

Here is a full working example I used:

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)
}

var repeatInterval: NSCalendarUnit

=> the docs say "The calendar interval at which to reschedule the notification."

so: use NSCalendarUnit.CalendarUnitDay

The other answers show how to use the old, pre iOS 10 local notifications. With iOS 10 and later, you must use UNNotificationCenter as follows:

    let content = UNMutableNotificationContent()
    content.title = "This will appear in bold, on it's own line."
    content.subtitle = "This will appear in bold, on it's own line, below the title."
    content.body = "This will appear as normal text, below the title and subtitle."

    let triggerInputForHourlyRepeat = Calendar.current.dateComponents([.minute], from: intendedFireDateVariable)
    let trigger = UNCalendarNotificationTrigger.init(dateMatching: triggerInput, repeats: true)

    let request = UNNotificationRequest(identifier: "someUniqueID", content: content, trigger: trigger)
    let unc = UNUserNotificationCenter.current()
    unc.add(request, withCompletionHandler: { (error) in
        /// Handle error
    })

Helpful tutorials:

  1. https://www.techotopia.com/index.php/An_iOS_10_Local_Notification_Tutorial
  2. https://makeapppie.com/2016/11/21/manage-delete-and-update-notifications-in-ios-10/
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!