How to create cross platform continuous(even in background as well) running Timer for iOS and Android in React Native?

190 Views Asked by At

I want to create a continuous running timer in react native that will run in the background as well in the app if I move to another screen.

I have used react-native-background-timer but that is not working on iOS Platform

is there any way to achieve this? Any help will be appreciated

Thanks

2

There are 2 best solutions below

1
Arik Segal On

For iOS, the following Swift function executes a code block after a given delay, even if the app is not active:

private var backgroundTaskId = UIBackgroundTaskIdentifier.invalid

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)
            }
        }
    }
}
0
Aleksandr Golovatyi On

Try to check on checkbox "Background processing" in the Background modes section. Take a look on the screenshot enter image description here