I'm trying to trigger local notifications for every 1 minute even in terminated state and background state. But, my app should not trigger notification when time is after 06:00PM. Below is my code.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,repeats: true)
//UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// 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.
}
}
}
To handle local notification, try this:
public func addLocalNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
// Initialize
let center = UNUserNotificationCenter.current()
// Set its content
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
// whenever you want to notify user select time
var dateComp = DateComponents()
dateComp.calendar = Calendar.current
dateComp.hour = hour
dateComp.minute = minute
// repeat and date
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComp, repeats: true)
// Initializing the Notification Request object
let req = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
// Add the notification to the center
center.add(req) { (error) in
if (error) != nil {
print(error!.localizedDescription)
}
}
}
I have problems setting a notification of type UNCalendarNotificationTrigger that is determined by DateComponents
//set content
let content = UNMutableNotificationContent()
content.title = "My Notification Management Demo"
content.subtitle = "Timed Notification"
content.body = "Notification"
content.body = "Notification pressed \(pressed) times"
content.categoryIdentifier = "message"
//set trigger possible problem
let formatted = DateFormatter()
formatted.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
formatted.date(from: "2018-01-19T02:29:50+0000")
var dateInfo = DateComponents()
dateInfo.calendar = formatted.calendar
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateInfo,
repeats: false
)
//Create the request
let request = UNNotificationRequest(
identifier: "my.notification",
content: content,
trigger: trigger
)
//Schedule the request
UNUserNotificationCenter.current().add(request) { (error : Error?) in
print("all ok")
}
And when I make a request to get the pending notifications, the array is wide.
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: {requests -> () in
print("\(requests.count) requests -------")
for request in requests{
print(request.identifier)
}
})
I've set the user notification. They got deliver well but the badge on the app icon is always one.
Here's my code:
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound];
center.requestAuthorization(options: options) {
(granted, error) in
if !granted {
// ask for permission
}
}
When the use click the button i schedule the notif:
#IBAction func saveBtnPressed(sender: UIButton) {
scheduleNotif()
}
Here's the scheduleNotif function
func scheduleNotif() {
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.medium
dateformatter.timeStyle = DateFormatter.Style.short
let dateFromString = dateformatter.date(from: selectDateTextField.text!)
let fireDateOfNotification: Date = dateFromString!
//Notif are enabled
let content = UNMutableNotificationContent()
content.title = notifTitleTextField.text!
content.body = notifNoteTextView.text
content.sound = UNNotificationSound.default()
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
var trigger: UNCalendarNotificationTrigger
var triggerDate = DateComponents()
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let titleNospace = notifTitleTextField.text?.replacingOccurrences(of: " ", with: "")
var identifier = titleNospace
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
self.center.add(request, withCompletionHandler: { (error) in
if let error = error {
print(error.localizedDescription)
}
})
}
Any idea why the badge will always display one and never increment as the notifications are delivered?
Thank you
I think you need to increment applicationIconBadgeNumber. So replace
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
By:
UIApplication.shared.applicationIconBadgeNumber += 1
content.badge = UIApplication.shared.applicationIconBadgeNumber as NSNumber
I'm creating an app that delivers daily local notifications at a time specified by the user via the app interface.
During testing, I schedule 20 daily local notifications to cover 20 days. On the last day, it's up to the user to tap the button to schedule 20 more.
When I run the app, it only sends the first notification. The remaining notifications never get sent. How can I fix my code so that the time is incremented by one day?
// Function that schedules the 20 notifications in advance so each one is delivered every day
func scheduleNotif() {
// Notification #1
let content = UNMutableNotificationContent()
content.title = "Good Morning \(name)!"
content.body = sendMessage()
content.sound = UNNotificationSound.default()
// Time in which notification will fire
let dailyTime = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dailyTime, repeats: false)
// The identifier for the notification so that it is distinguishable from others in code
let identifier = "Positive Message"
// Requesting for notification to be delivered
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #2
let content1 = UNMutableNotificationContent()
content1.title = "Good Morning \(name)!"
content1.body = sendMessage()
content1.sound = UNNotificationSound.default()
var dailyTime1 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime1.hour! += 24
let trigger1 = UNCalendarNotificationTrigger(dateMatching: dailyTime1, repeats: false)
let identifier1 = "Positive Message1"
let request1 = UNNotificationRequest(identifier: identifier1, content: content1, trigger: trigger1)
center.add(request1) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #3
let content2 = UNMutableNotificationContent()
content2.title = "Good Morning \(name)!"
content2.body = sendMessage()
content2.sound = UNNotificationSound.default()
var dailyTime2 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime2.hour! += 48
let trigger2 = UNCalendarNotificationTrigger(dateMatching: dailyTime2, repeats: false)
let identifier2 = "Positive Message2"
let request2 = UNNotificationRequest(identifier: identifier2, content: content2, trigger: trigger2)
center.add(request2) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #4
let content3 = UNMutableNotificationContent()
content3.title = "Good Morning \(name)!"
content3.body = sendMessage()
content3.sound = UNNotificationSound.default()
var dailyTime3 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime3.hour! += 72
let trigger3 = UNCalendarNotificationTrigger(dateMatching: dailyTime3, repeats: false)
let identifier3 = "Positive Message3"
let request3 = UNNotificationRequest(identifier: identifier3, content: content3, trigger: trigger3)
center.add(request3) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #5
let content4 = UNMutableNotificationContent()
content4.title = "Good Morning \(name)!"
content4.body = sendMessage()
content4.sound = UNNotificationSound.default()
var dailyTime4 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime4.hour! += 96
let trigger4 = UNCalendarNotificationTrigger(dateMatching: dailyTime4, repeats: false)
let identifier4 = "Positive Message4"
let request4 = UNNotificationRequest(identifier: identifier4, content: content4, trigger: trigger4)
center.add(request4) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #6
let content5 = UNMutableNotificationContent()
content5.title = "Good Morning \(name)!"
content5.body = sendMessage()
content5.sound = UNNotificationSound.default()
var dailyTime5 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime5.hour! += 120
let trigger5 = UNCalendarNotificationTrigger(dateMatching: dailyTime5, repeats: false)
let identifier5 = "Positive Message5"
let request5 = UNNotificationRequest(identifier: identifier5, content: content5, trigger: trigger5)
center.add(request5) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #7
let content6 = UNMutableNotificationContent()
content6.title = "Good Morning \(name)!"
content6.body = sendMessage()
content6.sound = UNNotificationSound.default()
var dailyTime6 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime6.hour! += 144
let trigger6 = UNCalendarNotificationTrigger(dateMatching: dailyTime6, repeats: false)
let identifier6 = "Positive Message6"
let request6 = UNNotificationRequest(identifier: identifier6, content: content6, trigger: trigger6)
center.add(request6) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #8
let content7 = UNMutableNotificationContent()
content7.title = "Good Morning \(name)!"
content7.body = sendMessage()
content7.sound = UNNotificationSound.default()
var dailyTime7 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime7.hour! += 168
let trigger7 = UNCalendarNotificationTrigger(dateMatching: dailyTime7, repeats: false)
let identifier7 = "Positive Message7"
let request7 = UNNotificationRequest(identifier: identifier7, content: content7, trigger: trigger7)
center.add(request7) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #9
let content8 = UNMutableNotificationContent()
content8.title = "Good Morning \(name)!"
content8.body = sendMessage()
content8.sound = UNNotificationSound.default()
var dailyTime8 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime8.hour! += 192
let trigger8 = UNCalendarNotificationTrigger(dateMatching: dailyTime8, repeats: false)
let identifier8 = "Positive Message8"
let request8 = UNNotificationRequest(identifier: identifier8, content: content8, trigger: trigger8)
center.add(request8) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #10
let content9 = UNMutableNotificationContent()
content9.title = "Good Morning \(name)!"
content9.body = sendMessage()
content9.sound = UNNotificationSound.default()
var dailyTime9 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime9.hour! += 216
let trigger9 = UNCalendarNotificationTrigger(dateMatching: dailyTime9, repeats: false)
let identifier9 = "Positive Message9"
let request9 = UNNotificationRequest(identifier: identifier9, content: content9, trigger: trigger9)
center.add(request9) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #11
let content10 = UNMutableNotificationContent()
content10.title = "Good Morning \(name)!"
content10.body = sendMessage()
content10.sound = UNNotificationSound.default()
var dailyTime10 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime10.hour! += 240
let trigger10 = UNCalendarNotificationTrigger(dateMatching: dailyTime10, repeats: false)
let identifier10 = "Positive Message10"
let request10 = UNNotificationRequest(identifier: identifier10, content: content10, trigger: trigger10)
center.add(request10) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #12
let content11 = UNMutableNotificationContent()
content11.title = "Good Morning \(name)!"
content11.body = sendMessage()
content11.sound = UNNotificationSound.default()
var dailyTime11 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime11.hour! += 264
let trigger11 = UNCalendarNotificationTrigger(dateMatching: dailyTime11, repeats: false)
let identifier11 = "Positive Message11"
let request11 = UNNotificationRequest(identifier: identifier11, content: content11, trigger: trigger11)
center.add(request11) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #13
let content12 = UNMutableNotificationContent()
content12.title = "Good Morning \(name)!"
content12.body = sendMessage()
content12.sound = UNNotificationSound.default()
var dailyTime12 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime12.hour! += 288
let trigger12 = UNCalendarNotificationTrigger(dateMatching: dailyTime12, repeats: false)
let identifier12 = "Positive Message12"
let request12 = UNNotificationRequest(identifier: identifier12, content: content12, trigger: trigger12)
center.add(request12) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #14
let content13 = UNMutableNotificationContent()
content13.title = "Good Morning \(name)!"
content13.body = sendMessage()
content13.sound = UNNotificationSound.default()
var dailyTime13 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime13.hour! += 312
let trigger13 = UNCalendarNotificationTrigger(dateMatching: dailyTime13, repeats: false)
let identifier13 = "Positive Message13"
let request13 = UNNotificationRequest(identifier: identifier13, content: content13, trigger: trigger13)
center.add(request13) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #15
let content14 = UNMutableNotificationContent()
content14.title = "Good Morning \(name)!"
content14.body = sendMessage()
content14.sound = UNNotificationSound.default()
var dailyTime14 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime14.hour! += 336
let trigger14 = UNCalendarNotificationTrigger(dateMatching: dailyTime14, repeats: false)
let identifier14 = "Positive Message14"
let request14 = UNNotificationRequest(identifier: identifier14, content: content14, trigger: trigger14)
center.add(request14) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #16
let content15 = UNMutableNotificationContent()
content15.title = "Good Morning \(name)!"
content15.body = sendMessage()
content15.sound = UNNotificationSound.default()
var dailyTime15 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime15.hour! += 360
let trigger15 = UNCalendarNotificationTrigger(dateMatching: dailyTime15, repeats: false)
let identifier15 = "Positive Message15"
let request15 = UNNotificationRequest(identifier: identifier15, content: content15, trigger: trigger15)
center.add(request15) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #17
let content16 = UNMutableNotificationContent()
content16.title = "Good Morning \(name)!"
content16.body = sendMessage()
content16.sound = UNNotificationSound.default()
var dailyTime16 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime16.hour! += 384
let trigger16 = UNCalendarNotificationTrigger(dateMatching: dailyTime16, repeats: false)
let identifier16 = "Positive Message16"
let request16 = UNNotificationRequest(identifier: identifier16, content: content16, trigger: trigger16)
center.add(request16) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #18
let content17 = UNMutableNotificationContent()
content17.title = "Good Morning \(name)!"
content17.body = sendMessage()
content17.sound = UNNotificationSound.default()
var dailyTime17 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime17.hour! += 408
let trigger17 = UNCalendarNotificationTrigger(dateMatching: dailyTime17, repeats: false)
let identifier17 = "Positive Message17"
let request17 = UNNotificationRequest(identifier: identifier17, content: content17, trigger: trigger17)
center.add(request17) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #19
let content18 = UNMutableNotificationContent()
content18.title = "Good Morning \(name)!"
content18.body = sendMessage()
content18.sound = UNNotificationSound.default()
var dailyTime18 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime18.hour! += 432
let trigger18 = UNCalendarNotificationTrigger(dateMatching: dailyTime18, repeats: false)
let identifier18 = "Positive Message18"
let request18 = UNNotificationRequest(identifier: identifier18, content: content18, trigger: trigger18)
center.add(request18) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
// Notification #20
let content19 = UNMutableNotificationContent()
content19.title = "Good Morning \(name)!"
content19.body = "Please open our app and update your time to keep recieving notifications!"
content19.sound = UNNotificationSound.default()
var dailyTime19 = Calendar.current.dateComponents([.hour, .minute,], from: timePick.date)
dailyTime19.hour! += 456
let trigger19 = UNCalendarNotificationTrigger(dateMatching: dailyTime18, repeats: false)
let identifier19 = "Positive Message19"
let request19 = UNNotificationRequest(identifier: identifier19, content: content19, trigger: trigger19)
center.add(request19) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
// Connecting the button to the code
#IBAction func timeSet(_ sender: AnyObject) {
let center = UNUserNotificationCenter.current()
// Setting users name
name = nameText.text!
// Configuring time
timePick.timeZone = NSTimeZone.local
timePick.locale = NSLocale.current
// Scheduling notification
center.removeAllPendingNotificationRequests()
center.removeAllDeliveredNotifications()
scheduleNotif()
}
}
You set your notification fine. But please rethink your code.
like in some function try to use like this. I am not writing your code just an example to help you to understand
func someFunction() {
for i in 1..<21 {
var notificationR = UILocalNotification()
notificationR = setUpNotification(notificationR)
notificationR.fireDate = Date.init(timeIntervalSinceNow: Double(i))
notificationR = publishLocalNotification(notificationR)
}
}
func setUpNotification(_ notification: UILocalNotification) -> UILocalNotification {
notification.alertBody = "Positive message"
notification.soundName = UILocalNotificationDefaultSoundName
notification.timeZone = TimeZone.current
notification.repeatInterval = NSCalendar.Unit.day
return notification
}
func publishLocalNotification(_ notification: UILocalNotification) -> UILocalNotification {
UIApplication.shared.applicationIconBadgeNumber = 0
UIApplication.shared.scheduleLocalNotification(notification)
return notification
}
I'm using the WatchOS 3 beta and trying to initiate a local notification on the watch. The interface is just one button which calls the "buttonPushed" method in the code below. The app runs fine but I never get a notification. The app structure is the default from Xcode 8 for a WatchKit app.
This code is in the InterfaceController.swift file of the WatchKit extension
Am I missing something totally obvious?
#IBAction func buttonPushed() {
sendMyNotification()
}
func sendMyNotification(){
if #available(watchOSApplicationExtension 3.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "REMINDER_CATEGORY"
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
center.add(request ,withCompletionHandler: nil)
} else {
// Fallback on earlier versions
}
}
According to this. You should specify a unique and new identifier for request each time.
Mine:
let id = String(Date().timeIntervalSinceReferenceDate)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
Swift 4 simple code
let content = UNMutableNotificationContent()
content.title = "How many days are there in one year"
content.subtitle = "Do you know?"
content.body = "Do you really know?"
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
Local Notification watchOS swift 4.0
var content = UNMutableNotificationContent()
content.title = "ALERT !"
content.body = msg
content.sound = UNNotificationSound.default() as? UNNotificationSound
// Time
var trigger: UNTimeIntervalNotificationTrigger?
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
// Actions
var snoozeAction = UNNotificationAction(identifier: "Track", title: "Track", options: .foreground)
var category = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction], intentIdentifiers: [] as? [String] ?? [String](), options: .customDismissAction)
var categories = Set<AnyHashable>([category])
center.setNotificationCategories(categories as? Set<UNNotificationCategory> ?? Set<UNNotificationCategory>())
content.categoryIdentifier = "UYLReminderCategory"
var identifier: String = stringUUID()
var request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request, withCompletionHandler: {(_ error: Error?) -> Void in
if error != nil {
print("Something went wrong: \(error)")
}
})
Unique request identifier methods
func stringUUID() -> String {
let uuid = UUID()
let str: String = uuid.uuidString
return str
}
Objective C
// Objective-C
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = #"ALERT !";
content.body = msg;
content.sound = [UNNotificationSound defaultSound];
// Time
UNTimeIntervalNotificationTrigger *trigger;
trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1
repeats:NO];
// Actions
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:#"Track"
title:#"Track" options:UNNotificationActionOptionForeground];
// Objective-C
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:#"UYLReminderCategory"
actions:#[snoozeAction] intentIdentifiers:#[]
options:UNNotificationCategoryOptionCustomDismissAction];
NSSet *categories = [NSSet setWithObject:category];
// Objective-C
[center setNotificationCategories:categories];
// Objective-C
content.categoryIdentifier = #"UYLReminderCategory";
NSString *identifier = [self stringUUID];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Something went wrong: %#",error);
}
}];
Unique request identifier methods
-(NSString *)stringUUID {
NSUUID *uuid = [NSUUID UUID];
NSString *str = [uuid UUIDString];
return str;
}