Swift:iBeacon在iOS结束进程之前运行代码

Swift:iBeacon在iOS结束进程之前运行代码,swift,ibeacon,Swift,Ibeacon,我在我的项目中实现了iBeacon认可,一切正常。当应用程序连接到具有IBeacon的BLE设备时,我启动一个将数据发送到服务器的整个过程。 我正在寻找一种方法来知道iOS何时在执行最后一个操作的10秒后终止应用程序。 我正在查看CLLocationManagerDelegate协议中的函数,但找不到类似willDisconnectApplication的函数 在iOS杀死我的应用程序以运行代码之前,我怎么知道还有一秒钟?您可以使用下面这样的代码片段来跟踪您有多少可用的后台时间 只需启动显示的后

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

您可以使用下面这样的代码片段来跟踪您有多少可用的后台时间

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


我应该把这段代码放在didRangeBeacon委托中的什么地方?您可以将关于private var backgroundTask的部分添加为一个新的类变量。将方法定义与所有其他方法一起添加。然后,在设置信标测距或监视时,需要至少调用extendBackgroundRunningTime一次。
  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);
        }
      }
    }
  }