Swift: iBeacon 在 iOS 结束该过程之前运行代码.



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

您可以使用如下所示的代码片段来跟踪可用的后台时间。

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

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);
}
}
}
}

最新更新