iOS Local notifications - ios

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

Related

How does iOS Local Notification Queueing work for UNTimeIntervalNotificationTrigger?

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)

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

Swift UNUsernotification applicationIconBadgeNumber displays always one

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

Resources