首页 > 解决方案 > Swift:iBeacon 在 iOS 结束进程之前运行代码

问题描述

我在我的项目中实现了 iBeacon 识别,一切正常。当应用程序连接到具有 IBeacon 的 BLE 设备时,我会启动一个将数据发送到服务器的整个过程。我正在寻找一种方法来了解 iOS 何时在 10 秒后终止应用程序以执行最后一个操作。我正在查看 CLLocationManagerDelegate 协议中的函数,但我找不到可能看起来像 willDisconnectApplication 的函数 在 iOS 杀死我的应用程序以运行代码之前我怎么知道一秒钟?

标签: swiftibeacon

解决方案


您可以使用如下所示的代码片段来跟踪您有多少可用的后台时间。

只需启动显示的后台任务,iOS 还会为您提供额外的后台运行时间,因此您将获得 180 秒而不是 10 秒。完成此操作后,您还可以通过查看来跟踪该时间即将到期的时间UIApplication.shared.backgroundTimeRemaining

  private var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

  func extendBackgroundRunningTime() {
    if (self.backgroundTask != UIBackgroundTaskInvalid) {
      // if we are in here, that means the background task is already running.
      // don't restart it.
      return
    }    
    self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "DummyTask", expirationHandler: {
      NSLog("Background running expired by iOS.  Cannot detect beacons again until a new region event")
      UIApplication.shared.endBackgroundTask(self.backgroundTask)
      self.backgroundTask = UIBackgroundTaskInvalid
    })

    if threadStarted {
      NSLog("Background task thread already started.")
    }
    else {
      threadStarted = true
      DispatchQueue.global().async {
        let startedTime = Int(Date().timeIntervalSince1970) % 10000000
        NSLog("Background task thread started")
        while (true) {
          let backgroundTimeRemaining = UIApplication.shared.backgroundTimeRemaining;
          if (backgroundTimeRemaining < 200.0) {
            if (backgroundTimeRemaining.truncatingRemainder(dividingBy: 30) < 1) {
              NSLog("Thread \(startedTime) background time remaining: \(backgroundTimeRemaining)")
            }
            else {
              NSLog("Thread \(startedTime) background time remaining: \(backgroundTimeRemaining)")
            }
          }
          Thread.sleep(forTimeInterval: 1);
        }
      }
    }
  }

推荐阅读