【发布时间】:2016-10-04 14:21:01
【问题描述】:
我正在开发一个连接到信标的应用程序。我能够运行该应用程序并在应用程序处于后台时检测信标(我在 didRangeBeacons 方法中发送本地通知并收到它们)。当检测到信标时,我需要在后台运行一段代码。我能怎么做?我试图在发送本地通知后准确地编写我的 Alamofire 调用,但没有任何反应。一些建议?
【问题讨论】:
标签: ios api background ibeacon
我正在开发一个连接到信标的应用程序。我能够运行该应用程序并在应用程序处于后台时检测信标(我在 didRangeBeacons 方法中发送本地通知并收到它们)。当检测到信标时,我需要在后台运行一段代码。我能怎么做?我试图在发送本地通知后准确地编写我的 Alamofire 调用,但没有任何反应。一些建议?
【问题讨论】:
标签: ios api background ibeacon
当应用程序在后台并收到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);
}
}
}
}
通过添加这样的代码,您的 Web 服务调用更有可能在 iOS 暂停您的应用程序之前完成。
您可以通过 didRangeBeacons 或 didEnterRegion 方法调用 extendBackgroundRunningTime()。
【讨论】:
当您收到 didEnter/didRange 回调时,您只有有限的时间在后台执行操作。
您应该结帐background tasks 以获得更多时间在后台调用您的服务器。
【讨论】: