Swift 3 - How to make timer work in background Swift 3 - How to make timer work in background ios ios

Swift 3 - How to make timer work in background


you can go to Capabilities and turn on background mode and active Audio. AirPlay, and picture and picture.

It really works . you don't need to set DispatchQueue .you can use of Timer.

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in   print("time")}


A timer can run in the background only if both the following are true:

  • Your app for some other reason runs in the background. (Most apps don't; most apps are suspended when they go into the background.) And:

  • The timer was running already when the app went into the background.


This works. It uses while loop inside async task, as suggested in another answer, but it is also enclosed within a background task

func executeAfterDelay(delay: TimeInterval, completion: @escaping(()->Void)){    backgroundTaskId = UIApplication.shared.beginBackgroundTask(        withName: "BackgroundSound",        expirationHandler: {[weak self] in            if let taskId = self?.backgroundTaskId{                UIApplication.shared.endBackgroundTask(taskId)            }        })        let startTime = Date()    DispatchQueue.global(qos: .background).async {        while Date().timeIntervalSince(startTime) < delay{            Thread.sleep(forTimeInterval: 0.01)        }        DispatchQueue.main.async {[weak self] in            completion()            if let taskId = self?.backgroundTaskId{                UIApplication.shared.endBackgroundTask(taskId)            }        }    }}


matomo