0

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

Shi Zhang
  • 143
  • 5
  • 18

1 Answers1

4

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.

MD Aslam Ansari
  • 1,565
  • 11
  • 19
  • You can check how to timer works here : https://stackoverflow.com/questions/24007518/how-can-i-use-nstimer-in-swift and : https://medium.com/ios-os-x-development/build-an-stopwatch-with-swift-3-0-c7040818a10f – MD Aslam Ansari Dec 07 '17 at 07:43
  • i have tried what you suggested but came up with the following issue: https://stackoverflow.com/questions/47732363/using-timer-to-set-local-notification-every-x-seconds – Shi Zhang Dec 09 '17 at 19:34