continuously setting new local notification - ios - ios

i am working on simulating an alarm.
in order to do so, i am trying to send a new local notification every X seconds while some condition is true and stopping while some condition is false (when the user cancels the alarm)
i have a Set button and a Stop button.
the following code is for when the Set button is pressed:
#IBAction func setNotification(_ sender: Any) {
// timeEntered = time.text!
// let hrMin = timeEntered.components(separatedBy: ":");
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
content.sound = UNNotificationSound(named: "alarm.aiff");
while (repeatNotifications) {
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false);
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
when the Stop button is pressed:
#IBAction func stopRepeat(_ sender: Any) {
repeatNotifications = false
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
right now, when i press the Set button, it is stuck in pressed mode (its color changes) and i can't press anything else (i.e.: Stop button) besides the home button. also, no local notifications is being set.
any ideas how to accomplish this?
tl;dr: how to set new local notifications every X seconds until some button is pressed

Your while condition is running more quickly then you think. It might be chocking your notification class by creating number of objects. Please use a timer to run every 5 seconds to push a notification.
You can use Instruments Tool to see the problem.

Related

How to send local notification to user when they leave the app IOS

I am working on a timer application that should terminate if the user leaves the app. I want a notification to be sent to the user when they leave the application. This notification WARNS the user that the timer will terminate if they do not return to the app immediately
I have look at UNNotficationTrigger's but not of what i have tried repeats the notification if the user is to be warned more than once.
How to i detect when the user is outside the application, then send a notification warning them to return to the app??
Thank you in advance
Code:
#IBAction func start(_ sender: Any) {
startTimer()
let content = UNMutableNotificationContent()
content.title = "WARNING: Return to 4ocus"
content.subtitle = ""
content.body = "Go back to 4ocus or risk losing 4ocus points"
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)
#IBAction func start(_ sender: Any) {
startTimer()
let content = UNMutableNotificationContent()
content.title = "WARNING: Return to 4ocus"
content.subtitle = ""
content.body = "Go back to 4ocus or risk losing 4ocus points"
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)
func applicationWillTerminate(_ application: UIApplication) {
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "Hey if you will not come back"
content.subtitle = "your timer will be killed"
content.body = ""
content.badge = 1
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
and also put the same code in willforeground method of appdelegate to get know if the user is about to leave application
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
put this method in your appdelegate and if there is alredy func applicationWillTerminate(_ application: UIApplication) is defined then put only code :)

using timer to set local notification every X seconds

i am trying to make an alarm app by setting new local notifications every X seconds when a Set button is pressed and stopping when the user taps a Stop button.
using Timer(), i am currently able to set the local notification but it doesn't repeat as I would like. it only repeats when i go into the app and back to the previous screen via the Home button. also, it only repeats once by doing that.
is there any way to have the user press the Set button once and have the notifications keep firing no matter if you're in the app/outside the app and only stopping when the user presses the Stop button?
my code as follows:
class LocalNotificationViewController: UIViewController {
var timer = Timer()
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: (#selector(self.setLocalNotification)), userInfo: nil, repeats: true)
}
#objc func setLocalNotification() {
// timeEntered = time.text!
// let hrMin = timeEntered.components(separatedBy: ":");
let content = UNMutableNotificationContent()
content.title = "Test Local Notification"
content.subtitle = "Testing..."
content.body = "Testing..."
content.badge = 1
content.sound = UNNotificationSound(named: "alarm.aiff");
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false);
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
var timeEntered: String = "";
var trigger: UNTimeIntervalNotificationTrigger? = nil;
#IBOutlet var time: UITextField!;
#IBAction func setNotification(_ sender: Any) {
runTimer()
}
#IBAction func stopRepeat(_ sender: Any) {
timer.invalidate()
}

How can I set the Local notification which fire every seconds after first set notification?

What I want that, I set the local notification for 7:00 am and as its fire immediately, notification comes continuously till the user not perform any action on notification or open the app.
below is code to send notification first time
let alarmNotification: UNMutableNotificationContent = UNMutableNotificationContent()
alarmNotification.title = "Demo"
alarmNotification.body = "Test"
alarmNotification.categoryIdentifier = "myDemoCategory"
let now = Date()
let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute], from: now)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let request = UNNotificationRequest(identifier: "TestNotification\(now)", content: alarmNotification, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
Please suggest for continuous send local notification.
Thanks
In your date component add seconds here
let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute], from: now)
set number of notifications you want in loop for every second by incrementing seconds Max is 64 in iOS.
when notification is tapped dismiss all notifications and reset for next time.

Geofence alerts/local notifications not waking up locked phone when triggered

I'm making an app that used circular regions for geofences. When the phone is active or the app is open, the geofence notifications are working fine in both simulator and device (iPhone 6 running 10.3.1).
In the simulator it works fine; When the user enters a region, it wakes up, makes a sound and shows an alert on the lock screen.
On the phone, the "didEnterRegion" delegate calls are made when entering the region (I log some messages) but the phone is not making an alert and waking up. When I push the home button once, I can see the alert on the lock screen, but I want it to wake up and show the alert instantly - like when I get a message. It works in the simulator, so I wonder what could be wrong? It has worked for me a few times, where the alert was shown on both the phone and my watch, but 95% of the time it's not working - the notifications are generated but only visible if I manually wake up the phone.
How to fix this?
Here's the code I use for creating the local notification:
// https://blog.codecentric.de/en/2016/11/setup-ios-10-local-notification/
let location = CLLocation(latitude: item.coordinate.latitude, longitude: item.coordinate.longitude)
GeoTools.decodePosition(location: location) {
(address, city) in
let content = UNMutableNotificationContent()
content.title = "Camera nearby!"
content.subtitle = item.id
content.body = "\(address), \(city)"
content.categoryIdentifier = Constants.notificationCategoryId
content.sound = UNNotificationSound.default()
content.threadIdentifier = item.id
// FIXME make action for clicking notification
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.001, repeats: false) // FIXME HACK
let request = UNNotificationRequest(identifier: "camNotification", content: content, trigger: trigger)
let unc = UNUserNotificationCenter.current()
unc.removeAllPendingNotificationRequests()
unc.add(request, withCompletionHandler: { (error) in
if let error = error {
print(error)
}
else {
print("completed")
}
})
}
Here is some code that I just verified wakes the device when notification is presented:
let message = "CLRegion event"
// Show an alert if application is active:
if UIApplication.shared.applicationState == .active {
if let viewController = UIApplication.shared.keyWindow?.rootViewController {
showSimpleAlertWithTitle(nil, message: message, viewController: viewController)
}
}
else {
// Otherwise app is in background, present a local notification:
let content = UNMutableNotificationContent()
content.body = message
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "message"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.0, repeats: false)
let request = UNNotificationRequest(identifier: "com.foobar", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Really the only diff is that I don't call removeAllPendingNotifications() so if you must remove notifications I wonder if removePendingNotificationRequests(withIdentifiers identifiers: [String]) might be more precise?

How to get a push notification at a set time? (Swift 3)

I'm making an app that's supposed the user everyday at a set time about the news. It get's the text of the news through a function which calls it from an array. My question is: how do I get my app to call the function and then send me a push notification with the info text every day at, let's say, 4am?
Thanks to everyone for answering! Have a great day!
Here is some code I used before. Not a hundred-percent what you are looking for, but I hope useful for you.
You need to modify it to be sending daily
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
var isGrantedNotificationAccess:Bool = false
#IBAction func send10SecNotification(_ sender: UIButton) {
if isGrantedNotificationAccess {
//add notification code here
//Set the content of the notification
let content = UNMutableNotificationContent()
content.title = "10 Second Notification Demo"
content.subtitle = "From MakeAppPie.com"
content.body = "Notification after 10 seconds - Your pizza is Ready!!"
//Set the trigger of the notification -- here a timer.
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 10.0,
repeats: true)
//Set the request for the notification from the above
let request = UNNotificationRequest(
identifier: "10.second.message",
content: content,
trigger: trigger
)
//Add the notification to the currnet notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
self.isGrantedNotificationAccess = granted
}
}
}

Resources