Nan
Nan

Reputation: 524

Issues regarding to Timer running in the background iOS 10

I am making an app that helps people with tracking down the working intervals.

What I need is the timer should run at least 30 minutes regardless of the app is in foreground or background.

func startFocus() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Pomodoro.focusIntervalCounter), userInfo: nil, repeats: true)
}

func focusIntervalCounter() {

    dynamic_focusIntervalSecond -= 1
    focusDelegate?.updatingFocusCountingDown(timeStamp: seconds2Timestamp(intSeconds: dynamic_focusIntervalSecond), secondLeft: dynamic_focusIntervalSecond)

    if dynamic_focusIntervalSecond == 0 {
        timer.invalidate()
        focusDelegate?.focusCountingDowndid(end: true)

    }
}

focusIntervalCounter() should invalid the timer when the `dynamic_focusIntervalSecond` is 0.

It works fine when the program is in the foreground, but after the screen is shut, the timer just works a little while and stop. Is this any approach to continue the timer's counting?

Thanks in advance.

Upvotes: 0

Views: 1000

Answers (3)

Tabz
Tabz

Reputation: 172

No, You cannot run Timers in background mode. You can create a UIBackgroundTaskIdentifier which will give you 180sec as i have observed, i'm not sure it might vary with OS version.

You can try scheduling local notifications for 30 mins.

You can enable back ground modes if you're using push notification, Airplay, Location, VOIP apps, Bluetooth, News stand, Background fetch, for more details read this apple developer document BackgroundExecution

Upvotes: 1

DariusV
DariusV

Reputation: 2773

Some things are not possible in background, Have you switched your project to enable the background modes? You can reed more about it here

Upvotes: 0

bjtitus
bjtitus

Reputation: 4270

No, you can run background tasks for up to 5 minutes, use the background update functionality to trigger app refresh, or use notifications to trigger background actions. There is no way in iOS to guarantee that any code will be run consistently in the background after 30 minutes. Local notifications will enable your code to run after the user selects an action in a notification. Silent push notifications can run some code in the background open receipt, but require an internet connection and are not guaranteed to be delivered.

See this question for more info: iOS Timer in the background

Upvotes: 1

Related Questions