Swift 3 - How to make timer work in 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) } } }}