How does iOS Local Notification Queueing work for UNTimeIntervalNotificationTrigger? - ios

If I create a simple app where I want one notification to be sent every minute for 4 consecutive minutes; after an initial 5 second delay.
When I call scheduleManyNotes() below, I print out the pending notifications and see only 1. What causes these notifications to be grouped together into 1?
func scheduleManyNotes() {
for x in 0...4 {
scheduleNote("note \(x)", (x * 60) + 5)
}
notificationCenter.getPendingNotificationRequests(completionHandler:{reqs in
for request in reqs {
print(request)
}
})
}
func scheduleNote(_ msg: String, _ delaySec: Int) {
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.body = msg
content.badge = NSNumber(integerLiteral: delaySec)
content.categoryIdentifier = msg
let trigger = delaySec == 0 ? nil : UNTimeIntervalNotificationTrigger(timeInterval: Double(delaySec), repeats: false)
let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
NSLog("Scheduling Request \(msg)")
notificationCenter.add(request) { (error) in
if let error = error {
NSLog("Error \(error.localizedDescription)")
}
}
}

The problem is that I was using the same identifier for all the TimeInterval notifications. One I changed the identifier to be unique for each request, I then had 5 unique requests.
// Original
let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
// Modfified
let uid = UUID.init().uuidString
print("hopefully unique uuid:\(uid)")
let request = UNNotificationRequest(identifier: uid, content: content, trigger: trigger)

Related

iOS Local notifications

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

swift display local notification even the app terminated

hello i want to send notification like daily reminder even the app terminated not working in background how i can do it and this my code
func soundNotification(){
let prayers = ["fajer","dohor","asr","maghreb","isha"]
let content = UNMutableNotificationContent()
content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
content.badge = 1
content.sound = UNNotificationSound(named: "salah.mp3")
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
func soundNotification(){
let prayers = ["fajer","dohor","asr","maghreb","isha"]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let content = UNMutableNotificationContent()
content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
content.body = " "
content.badge = 1
content.sound = UNNotificationSound(named: "salah.mp3")
let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
}
}
}
Trigger local Notification at date and time.
func scheduleNotification(at date: Date, message:String) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = message
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
}
}
}

How to set UNLocalNotification between two dates Swift

I am working on a medicine reminder app. The user will input two dates and I need to schedule local notifications between those two dates. I can't find how to specify the starting and the ending date in the UNNotificationRequest.
I have tried this:
static func setAlarmWithDate (hour:Int, minutes:Int , day:Int, medicineName:String, medicineId:String) {
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "MY_MEDICINE".localizedString(), arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "This is a notification for your medicine \(medicineName)",
arguments: nil)
content.sound = UNNotificationSound.default()
var userInfo = [String:String]()
let medicine = medicineId
userInfo["medicine"] = medicine
content.userInfo = userInfo
var dateInfo = DateComponents()
dateInfo.hour = hour
dateInfo.minute = minutes
dateInfo.weekday = day
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
let identifier = medicineId
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)
}
}
}
I am new to Swift and I am really stuck.

Problems in UNCalendarNotificationTrigger in Swift 4

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

Local Notification in WatchOS 3

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

Resources