我需要检查应用程序是否已移至后台。为什么?
嗯,因为我的应用程序与蓝牙配合使用,并且一次只能将一个人连接到此设备。因此,如果他们不使用它并且应用程序在后台运行,请断开他们的连接并将他们发送到连接主页。
现在我已经做到了。我在主要的第一类中有一个选择器和一个断开连接并发送到第一页的功能。但我没有意识到的是,如果向上拖动控制面板,应用程序将处于“后台”。
环顾四周,似乎没有办法检测是否启动了控制面板。那么有人对我如何以不同的方式执行此操作有任何想法吗?
实际上我只是想要它,所以如果应用程序由于任何其他原因而不是正在调出控制面板而被移至后台,请断开与设备的连接。
选择器:
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)
功能:
@objc func appMovedToBackground() {
if (ViewController.connectedPeripheral != nil) {
print("App moved to background!")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "connectView") as! ViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
ViewController.centralManager.cancelPeripheralConnection(ViewController.connectedPeripheral!)
}
else {
print("App moved to background but no device is connected so no further action taken")
}
}
这不是其他问题的重复。我知道如何检查应用程序是否处于后台状态。我只是不想在调出控制面板时断开连接...
最佳答案
在 Swift 中:
if UIApplication.shared.applicationState == .background {
// Add code here...
}
在 Objective-C 中:
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
// Add code here...
}
希望它有用!
关于ios - swift 3 : Checking if app is in background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45296962/