【问题标题】:How to create cross platform continuous(even in background as well) running Timer for iOS and Android in React Native?如何在 React Native 中创建跨平台连续(甚至在后台)运行 iOS 和 Android 的 Timer?
【发布时间】:2023-01-10 18:08:18
【问题描述】:

我想在 React Native 中创建一个连续运行的计时器,如果我移动到另一个屏幕,它将在后台以及应用程序中运行。

我使用了react-native-background-timer,但在 iOS 平台上不起作用

有什么办法可以做到这一点?任何帮助将不胜感激

谢谢

【问题讨论】:

    标签: ios react-native timer background-process timertask


    【解决方案1】:

    对于 iOS,以下 Swift 函数会在给定延迟后执行代码块,即使应用程序未处于活动状态也是如此:

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

    【讨论】:

      最近更新 更多