swift - 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);
}
}
}
}
推荐阅读
- python - Pandas:根据某些列的字符串值将数据框拆分为单独的数据框
- html - 最后移动
- 元素到容器底部,其余元素居中
- oracle - 使用 url_datastore 创建索引
- jenkins - Jenkins 与 intellij 共享库
- react-native - 套接字 io 反应本机问题(this.mapData 不是函数)
- java - O-Notation 练习题理解部分代码
- c++ - 具有比例和平移的 Arcball 旋转问题
- java - 试图通过 orderByChild() 通过电话订购,但它不起作用?
- r - 是否可以以编程方式添加 ggplot2 注释
- pelican - 如何从模板中获取 Pelican 版本号