Jeremy Gurr
Jeremy Gurr

Reputation: 1623

How to make a repeating countdown timer app for an iphone in swift 3 that fires a notification every 'x' minutes even when in the background

I'm trying to make a simple app that fires off an alarm every 7 minutes (configurable of course) whether the app is in the foreground or not.

Although it was easy enough to just make a hardcoded repeating timer that does this, adding any kind of front end interface seems to throw a wrench into my strategy, suggesting to me that maybe I am taking the wrong approach entirely.

For example, if I just have a start / stop button, pausing an existing timer needs to cancel the background notification, but keep track of how much time is left. Then when it is resumed, a notification needs to be recreated with the remaining time. For example, if it is a 5 minute timer, that is paused with only 2 minutes left, when it is resumed, it is set up to be a 2 minute countdown timer. So if I put the app in the background, I will get a notification that the time has elapsed, but it won't automatically start a 5 minute countdown, it will instead just go back to 2 minutes. I need to be able to create notifications that are repeating, and yet switch to the full duration once the "remaining" time has expired.

I could create an action on the notification, which if the user pressed would restart the timer, but for this purpose, I need the timer to automatically restart immediately, even if the user ignores it.

I could easily accomplish this with foreground timers, but then I would need to force my phone to never go to sleep, and it would only work while this app was in the foreground, which is not always possible on a phone.

Other timer apps can pop up background notifications just fine. And the calendar app can schedule background notifications for arbitrary times. I doubt the calendar app schedules all future (including repeating) alerts the moment it is started, since it works even if the phone was restarted and the calendar app never started. Therefore the calendar app notification mechanism must be smart enough to fire off an alarm, and then schedule the next alarm, which is exactly the kind of mechanism I need here. I thought maybe the calendar app just uses server-based remote notifications, and the server handled the more complex logic needed, but that can't be true since the calendar app notifications work fine even without any internet connection.

I've done a fair bit of research on this, but can't seem to find what to do. If I could pass in a tiny bit of code to be executed when the notification is triggered, that would work, but I see no way of doing that.

This is what my notification creation code looks like at the moment:

    let content = UNMutableNotificationContent()

    content.title = "Context switch"
    content.body = "\(Int(initialDuration / 60)) minutes have passed."
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = generalCatId

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: remaining, repeats: true)
    let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.delegate = self

    center.add(request) { (error) in
        if error != nil {
            print(error!)
        }
    }

Upvotes: 0

Views: 1218

Answers (1)

Henawey
Henawey

Reputation: 558

the five basic background modes available in iOS:

  1. Play audio the app can continue playing and/or recording audio in the background.
  2. Receive location updates the app can continue to get callbacks as the device’s location changes.
  3. Perform finite-length tasks the generic “whatever” case, where the app can run arbitrary code for a limited amount of time.
  4. Process Newsstand Kit downloads specific to Newsstand apps, the app can download content in the background.
  5. Provide Voice-over-IP (VoIP) services the app can run any arbitrary code in the background. Of course, Apple limits its use so that your app must provide VoIP service, too.

Ref

Sorry, you can run the timer in the background forever so you have to think to do something doesn't depend on Perform finite-length tasks background mode.

So you have 3 options:

  1. register your app to receive location updates and this need Requesting Permission to Use Location Services requestAlwaysAuthorization()

  2. check the device time every time you go to foreground and this will not work correctly if user changes the time manually so best thing to do is calling web service to get current time in UTC

    http://www.timeapi.org/utc/now

  3. register to local notification when your app sends to background

        var localNotification = UILocalNotification()
        localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
        localNotification.alertBody = "Time out"
        localNotification.timeZone = NSTimeZone.defaultTimeZone()
        localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    

then schedule this notification UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

Upvotes: 1

Related Questions