Run multiple notifications through a function in Swift in Xcode? - ios

I've created a function which will send the user a notification at a specific hour and minute with specified text. The problem is, when I call the function twice (trying to send two notifications), it only runs the second notification. Essentially, I need to be able to call the function multiple times to get multiple notifications at different times. My guess is calling it a second time overwrites the prior. Anyway I can fix/accomplish this? Here's my code:
func notification(hour: Int, minute: Int, text: String){
let content = UNMutableNotificationContent()
content.title = "Example"
content.body = text
content.sound = UNNotificationSound.default()
var date = DateComponents()
date.hour = hour
date.minute = minute
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let request = UNNotificationRequest(identifier: "testIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
notification(hour: 12, minute: 5, text: "It is 12:05.")
notification(hour: 12, minute: 10, text: "It is 12:10.")
}

It's because the same identifier
let request = UNNotificationRequest(identifier: "testIdentifier", content: content, trigger: trigger)
so change it for every scheduled notification

Related

Send local notification based on system time on Iphone?

In my app, a user will set date and time for reminder, and the phone needs to send local notification at that particular time even when the app is closed.
Able to send a notification at particular time using the below method. but it doesn't work when app is closed:
public func simpleAddNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
// Initialize User Notification Center Object
let center = UNUserNotificationCenter.current()
// The content of the Notification
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
content.badge = 1
// The selected time to notify the user
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = hour
dateComponents.minute = minute
// The time/repeat trigger
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Initializing the Notification Request object to add to the Notification Center
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
// Adding the notification to the center
center.add(request) { (error) in
if (error) != nil {
print(error!.localizedDescription)
}
}
}

automatically connect to API once a minute and show notification

I have a function with notification with the time interval trigger, which shows the notification once a minute
func addNotificationWithTimeIntervalTrigger(){
callApi()
let content = UNMutableNotificationContent()
print("PresentTitle",AppDelegate.titleNotification,"\(Date())")
content.title = AppDelegate.titleNotification
//content.subtitle = subTitle
//content.body = body
content.badge = 1
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats:true)
let reguest = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(reguest) { (error) in}
}
But it shows only one, the old value once a minute, although the data in API has already changed.
To see the new value, i need to press the button again, but I do not want that, i want to know how to rewrite this func that this (timeInterval: 60, repeats:true) includes callApi() or smth like that.
You can use NStimer for this .
var timer = NSTimer.scheduledTimerWithTimeInterval(60.0,
target: self,
selector: Selector("addNotificationWithTimeIntervalTrigger"),
userInfo: nil,
repeats: true)

Triggering all pending notifications before the time set for it

In the app I'm developing, there is an option for triggering notification x amount of time before the actual time set for the said notification. For example I set the reminder for 10:00. But in the app's local settings, I set the notification to trigger 10 minutes before the time set. So, in this example's case, the notification will trigger in 9:50.
Now, I can do the above when I'm setting time for individual notification. But what I want to do is trigger all pending notifications before the actual time set for it.
This is the function I'm using to set notifications:
func scheduleNotification(at date: Date, identifier: String, threadIdentifier: String, body: String) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, year: components.year, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "TestNotification"
content.body = body
content.threadIdentifier = threadIdentifier
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {
error in
if let error = error {
print("Error in delivering notification. Error: \(error.localizedDescription)")
}
}
}
The date is coming from the date set by the date picker. I tried to change trigger properties by using this code:
UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
for request in requests {
request.trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10*60, repeats: false)
}
}
But now I get an error saying 'trigger' is a get-only property.
There is no way to change fire time of a scheduled notification , you can remove all of them and re-schedule again

How to update the daily local notification message in iOS 10?

I'm trying to find out how to update the message in the local notifications when it is repeated daily.
Currently I have the following code in my AppDelegate:
func scheduler(at date: Date, numOfNotes: Int)
{
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
content.badge = numOfNotes as NSNumber
content.body = "REMINDER: " + String(numOfNotes) + " needs to be looked at!"
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "reminderNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request) {(error) in
}
}
I am storing numOfNotes in UserDefaults. I have a UISwitch in my UITableViewCell, that upon being switched on calls the scheduler function like so:
func remindMeSwitch(_ remindMeSwitch: UISwitch)
{
numOfNotes = UserDefaults.standard.integer(forKey: "Notes")
let delegate = UIApplication.shared.delegate as? AppDelegate
delegate?.scheduler(at: time, numOfNotes: numOfNotes)
}
However, when setting the repeats parameter to true to have the notification repeat daily at the specified time, numOfNotes is only called once, which is when I toggle the UISwitch on.
How can I set the notification to alert daily but still be able to update the notification message as needed?
Thanks.
In general, you don't have any possibility to change Local Notifications.
Only one way - delete/cancel the old notification and create the new notification. But you can use a copy function.
For example, if you want to change the notification's content:
// create new content (based on old)
if let content = notificationRequest.content.mutableCopy() as? UNMutableNotificationContent {
// any changes
content.title = "your new content's title"
// create new notification
let request = UNNotificationRequest(identifier: notificationRequest.identifier, content: content, trigger: notificationRequest.trigger)
UNUserNotificationCenter.current().add(request)
}

Local notifications - repeat Interval in swift 3

I want to repeat local notification every week, before iOS10 there is repeatInterval, but i am not able to find anything suitable to repeat notifications in iOS10.
TimeTrigger and calendarTrigger both have repeat as true or false, where can i apply repeat as weekly, daily, monthly.
Thanks.
Try this.
func scheduleNotification(at date: Date, body: String) {
let triggerWeekly = Calendar.current.dateComponents([.weekday,hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Dont Forget"
content.body = body
content.sound = UNNotificationSound.default()
//content.categoryIdentifier = "todoList"
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}

Resources