-1

I am just using NotifcationObserver in viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(backgroundRefreshStatusDidChange), name: UIApplication.didEnterBackgroundNotification, object: nil)

and using timer like this

@objc func backgroundRefreshStatusDidChange(notification: NSNotification) { print("New status: (UIApplication.shared.backgroundRefreshStatus)") timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) }

When app goes into the background mode, the Timer is Stoped but I want timer to running if app is background mode.

Kudos
  • 1,224
  • 9
  • 21
  • Did you add Background Mode to your Project. If dont Go Signing & Capability -> Click + Capability then add Background Modes – Omer Tekbiyik Dec 09 '22 at 13:09
  • Yes i added this but it's not working – Muhammad Manzar Dec 09 '22 at 13:27
  • You can follow https://stackoverflow.com/a/50383839/9110909. But read the comments too. If your app doesn't use this mode (Audio,Airplay, and Picture in Picture). Apple going to reject your app. – Omer Tekbiyik Dec 09 '22 at 15:56
  • Timers do not run in the background. There is no way to make a timer run in the background. You probably don't need your timer to run in the background. What do you want to do when the timer fires? There may be other strategies. – Paulw11 Dec 09 '22 at 19:46
  • when my OTP screen is open the timer is start and resend button is enable after 3mins counter my requirement is when i move my app background the timer is stop i just want timer is running if my app go background but it's does not work when my app go in background – Muhammad Manzar Dec 12 '22 at 06:08

1 Answers1

-1

You need to start timer on global Dispatch Queue like so:

@objc func backgroundRefreshStatusDidChange(notification: NSNotification) {
    print("New status: (UIApplication.shared.backgroundRefreshStatus)")
    DispatchQueue.global().async {
        self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
}