首页 > 解决方案 > 在 Swift 4.2 中,后台获取每秒都在工作

问题描述

看哪。我正在尝试使用 swift 4.2 创建一个 IOS 应用程序,据我的客户说,它必须发出警报,但只能通过 QR 码停止。因此,我需要一个在后台工作的计时器,每秒钟检查一次时间,因为别的东西,用户可以在没有二维码的情况下停止它。我唯一找到的就是后台提取,但它可以每次都进行 1 秒检查吗?

有没有人有更好的主意?

干杯

这是我现在的源代码

应用委托:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     UIApplication.shared.setMinimumBackgroundFetchInterval(2.0)
}

//ini----------------------------background task
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // fetch data from internet now
    let time:TimerNow = TimerNow();
    let hours = preferences.string(forKey: "hours");
    let minutes = preferences.string(forKey: "minutes");
    if((hours == time.getHours())&&(minutes == time.getMinutes())){
        lem.onPlayCommand();
    }
    completionHandler(.newData)
}
//fin ---------------------------background task

标签: swiftbackgroundfetchalarm

解决方案


我认为您应该改用本地通知。当您想要通知已用时间时,它将被触发。您可以随时以任何您想要的条件取消它。

IMO 计时器和后台获取不适合这种情况。


推荐阅读