我正在开发一个连接信标的应用程序。我可以运行该应用程序,还可以在应用程序处于后台时检测到信标(我在didRangeBeacons方法中发送了本地通知,并且收到了它们)。当检测到信标时,我需要在后台运行一段代码。我能怎么做?发送本地通知后,我试图写Alamofire call ,但是什么也没发生。有什么建议吗?
最佳答案
当应用程序在后台运行并获得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暂停应用程序之前完成。
您可以通过
extendBackgroundRunningTime()
或didRangeBeacons
方法调用didEnterRegion
。
关于ios - 信标范围在后台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39854759/