信标范围在背景中

时间:2016-10-04 14:21:01

标签: ios api background ibeacon

我正在开发一个连接到信标的应用程序。我可以运行应用程序并在应用程序处于后台时检测信标(我在didRangeBeacons方法中发送本地通知并收到它们)。当检测到信标时,我需要在后台运行一段代码。我能怎么做?在发送本地通知后,我试图写完我的Alamofire电话,但没有任何反应。一些建议?

2 个答案:

答案 0 :(得分:2)

当应用在后台并且获得didRangeBeacons回调时,操作系统在暂停之前仅运行5秒。这将关闭当时打开的所有Web服务连接。您可以根据请求将此后台运行时间从5秒延长到180秒。下面是Swift 3中的一个示例,说明了如何执行此操作。

var threadStarted = false
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
  }

  print("Attempting to extend background running time")

  self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "DummyTask", expirationHandler: {
    UIApplication.shared.endBackgroundTask(self.backgroundTask)
    self.backgroundTask = UIBackgroundTaskInvalid
  })

  if threadStarted {
    print("Background task thread already started.")
  }
  else {
    threadStarted = true
    DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
      while (true) {
        // A dummy tasks must be running otherwise iOS suspends immediately
        Thread.sleep(forTimeInterval: 1);
      }
    }
  }
}

通过添加这样的代码,您的网络服务调用更有可能在iOS暂停您的应用之前完成。

您可以使用extendBackgroundRunningTime()didRangeBeacons方法拨打didEnterRegion

答案 1 :(得分:0)

当你获得didEnter / didRange回调时,你只有有限的时间在后台做东西。

您应该结帐background tasks以便在后台获得更多时间来呼叫您的服务器。