0
votes

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

1
You might have to mention what exactly you want to achieve with this feature? Are you trying to develop an alarm app ?MD Aslam Ansari
@MDAslamAnsari, i have added it to the beginning of the question!Shi Zhang

1 Answers

4
votes

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.