背景中的信标范围
Beacon range in background
我正在开发一个连接到信标的应用程序。我能够 运行 应用程序,还可以在应用程序处于后台时检测信标(我在 didRangeBeacons 方法中发送本地通知并收到它们)。当检测到信标时,我需要在后台 运行 一段代码。我能怎么做?我试图在发送本地通知后准确地编写我的 Alamofire 调用,但没有任何反应。一些建议?
当您收到 didEnter/didRange 回调时,您只有有限的时间在后台执行操作。
您应该检查 background tasks 以获得更多时间在后台调用您的服务器。
当应用程序在后台并获得 didRangeBeacons
回调时,它只需要 5 秒就被操作系统运行 挂起.这将关闭当时打开的所有 Web 服务连接。您可以根据要求将此后台 运行ning 时间从 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()
。
我正在开发一个连接到信标的应用程序。我能够 运行 应用程序,还可以在应用程序处于后台时检测信标(我在 didRangeBeacons 方法中发送本地通知并收到它们)。当检测到信标时,我需要在后台 运行 一段代码。我能怎么做?我试图在发送本地通知后准确地编写我的 Alamofire 调用,但没有任何反应。一些建议?
当您收到 didEnter/didRange 回调时,您只有有限的时间在后台执行操作。
您应该检查 background tasks 以获得更多时间在后台调用您的服务器。
当应用程序在后台并获得 didRangeBeacons
回调时,它只需要 5 秒就被操作系统运行 挂起.这将关闭当时打开的所有 Web 服务连接。您可以根据要求将此后台 运行ning 时间从 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()
。