iOS Web View Gets Stuck when ever the app goes to background and comes to foreground

311 Views Asked by At

We have a web-view which hosts a web action sheet with a timer. Whenever there is a navigation to a different app and back to our app, the timer gets stuck and the web action sheet becomes unresponsive.

Any solutions or work around to solve this issue ?

1

There are 1 best solutions below

0
On

Use the following function to create a timer that keeps working when the app is in background:

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)
            }
        }
    }
}