How to send a localNotification at a specific time everyday, even if that time has passed?
Updated @Paulw11 's answer to Swift 3.0 and wrapped up in a function:
/// Set up the local notification for everyday
/// - parameter hour: The hour in 24 of the day to trigger the notification
class func setUpLocalNotification(hour: Int, minute: Int) {
// have to use NSCalendar for the components
let calendar = NSCalendar(identifier: .gregorian)!;
var dateFire = Date()
// if today's date is passed, use tomorrow
var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire)
if (fireComponents.hour! > hour
|| (fireComponents.hour == hour && fireComponents.minute! >= minute) ) {
dateFire = dateFire.addingTimeInterval(86400) // Use tomorrow's date
fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire);
}
// set up the time
fireComponents.hour = hour
fireComponents.minute = minute
// schedule local notification
dateFire = calendar.date(from: fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertBody = "Record Today Numerily. Be completely honest: how is your day so far?"
localNotification.repeatInterval = NSCalendar.Unit.day
localNotification.soundName = UILocalNotificationDefaultSoundName;
UIApplication.shared.scheduleLocalNotification(localNotification);
}
UNNotificationRequest to send local notification daily at a specific time
You can use UNCalendarNotificationTrigger
for creating a notification that fires repeatedly using UNUserNotificationCenter
. You can do something like this. The trick is to only have the time component in the Trigger date.
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Attention!"
content.body = "Your daily alert is ready for you!"
content.sound = UNNotificationSound.default
let identifier = "com.yourdomain.notificationIdentifier"
var triggerDate = DateComponents()
triggerDate.hour = 18
triggerDate.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print("Error : \(error.localizedDescription)")
} else {
// Something went right
print("Success")
}
})
How do I schedule a notification at a specific time, and then repeat it every x amount of time?
From what I know it's not possible to repeat a notification every X seconds (or something else) after a specific date.
I think the "best" option here is to use UNCalendarNotificationTrigger
instead and schedule 60/5 = 12 notification (so 1 every 5 seconds) starting from the given date.
Something like this:
// this is your reference date - here it's now + 5 seconds just for this example
var referenceDate = Calendar.current.date(byAdding: .second, value: 5, to: Date())!
for i in 0...11 { // one every 5 seconds, so total = 12
let content = UNMutableNotificationContent()
content.title = "Notif \(i)"
content.body = "Body"
var dateComponents = DateComponents(calendar: Calendar.current)
// 5 seconds interval here but you can set whatever you want, for hours, minutes, etc.
dateComponents.second = 5
//dateComponents.hour = X
// [...]
guard let nextTriggerDate = dateComponents.calendar?.date(byAdding: dateComponents, to: referenceDate),
let nextTriggerDateCompnents = dateComponents.calendar?.dateComponents([.second], from: nextTriggerDate) else {
return
}
referenceDate = nextTriggerDate
print(nextTriggerDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: nextTriggerDateCompnents, repeats: true)
let request = UNNotificationRequest(identifier: "notif-\(i)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
Now based on that, you would need to handle when a user taps one of the notifications in order to cancel all the others. But that's another topic here and I leave it up to you to find the logic for that.
how to set local notifications between 8am and 8pm every day
Unfortunately you do need to add a notification request for each 30 minute interval in the 8am-8pm window. What is your aversion to this approach? It's a simple for-loop. Instead of using a UNTimeIntervalNotificationTrigger
you would use a UNCalendarNotificationTrigger
.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
let startHour = 8
let totalHours = 12
let totalHalfHours = totalHours * 2
for i in 0...totalHalfHours {
var date = DateComponents()
date.hour = startHour + i / 2
date.minute = 30 * (i % 2)
print("\(date.hour!):\(date.minute!)")
let notification = UNMutableNotificationContent()
notification.title = "You should have some water"
notification.body = "It has been a long time since you had some water, why don't you have some."
notification.categoryIdentifier = "reminder"
notification.sound = .default
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
}
iOS local notification base on day, time frame and number of times?
If you want to schedule multiple notifications, you need to create multiple notification triggers and register them.
something like:
// Simple extension if you have to create multiple of the same object
extension DateComponents {
static func triggerFor(hour: Int, minute: Int) -> DateComponents {
var component = DateComponents()
component.calendar = Calendar.current
component.hour = hour
component.minute = minute
component.weekday = 1
return component
}
}
// Add each trigger into an array with the correct date component
let triggers = [
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 1, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 2, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 3, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 4, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 5, minute: 0), repeats: true)
]
// Iterate through the array and register the notification with the system
for trigger in triggers {
// Create the content of the notification
let content = UNMutableNotificationContent()
content.title = "My Notification Title"
content.body = "Body of Notification"
// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// Handle any errors.
}
}
}
Repeating local notification daily at a set time with swift
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
How do I set up a repeating daily notification with different content each time?
Ok, here is the solution for this.
It is NOT possible to schedule a repeating notification with a random content each day. The content is defined when the notification is scheduled, and cannot be changed later.
What you CAN do it schedule up to 64 notifications in advance though. So you can schedule 64 unique notifications for the next 64 days, and then whenever you open the app check how many remain, and fill up the notification-schedule up to 64 again.
If you don't open the app after 64 days the notifications stop coming though :P
How do I send local notifications at a specific time in Swift?
This is an example of what I have used for scheduling local notifications using Notification Centre.
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "My title"
content.body = "Lots of text"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "yourIdentifier"
content.userInfo = ["example": "information"] // You can retrieve this when displaying notification
// Setup trigger time
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
let testDate = Date() + 5 // Set this to whatever date you need
let trigger = UNCalendarNotificationTrigger(dateMatching: testDate, repeats: false)
// Create request
let uniqueID = UUID().uuidString // Keep a record of this if necessary
let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
center.add(request) // Add the notification request
The Date
object (represented by testDate
above) can be whatever date you want. It is often convenient to create it from DateComponents
.
You will need to ask permission for local notifications in the App Delegate at startup to allow this to work. Here is an example.
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Ask permission for notifications
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Permission granted")
} else {
print("Permission denied\n")
}
}
}
}
How Can I Repeat Local Notifications for Evey Hours in Every Day?
let interval:TimeInterval = 60.0 // 1 minute = 60 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)
Use UNTimeIntervalNotificationTrigger
instead of UNCalendarNotificationTrigger
because UNCalendarNotificationTrigger
object is used when you want to schedule the delivery of a local notification at the specified date and time and UNTimeIntervalNotificationTrigger
object is used when you want to schedule the delivery of a local notification after the specified number of seconds elapse.
https://developer.apple.com/documentation/usernotifications/untimeintervalnotificationtrigger
Related Topics
Can't Build an App for Distribution After Joining Existing Enterprise Developer Program
API Call Error in Xcode 7/iOS 9 (How to Setup App Transport Security in Plist)
Uialertview's Textfield Does Not Show Keyboard in iOS8
How to Make a Nsurlsesssion Get Request with Cookies
Uicollectionviewcompositionallayout - Center Items in Sections or Groups
Xcode Export App, Wildcard Error
How to Add Pagination in UItableview.
How to Detect If My Device Is an iPhone x in Swift 4
iOS Google Maps Sdk Gmsmarker Positioning
Scenekit Flattenedclone - Incorrect Use of Objc_Storeweak() and Objc_Loadweak() Error
How to Launch IPA File in iOS 10 Real Device Using Appium 1.6.0
Swift 3: Transfer Utility Enumeratetoassignblocks Method Signature
Custom Uibarbuttonitem with Bg Colour and Text Swift 3
How to Dismiss a Modal Segue Then Perform Push Segue to New View Controller
How to Rotate a UIview Without The Black Bars
App Could Not Authenticate with Facebook and Firebase After Conversion to Swift 3 Syntax