在AppDelegate中的applicationDidEnterBackground时调用ViewController

时间:2018-03-26 14:40:51

标签: swift bluetooth background viewcontroller appdelegate

我正在开发一款应用程序,用于在后台扫描特定的UUID蓝牙设备(后台应用程序)并与之连接(ViewController称为“BluetoothScanVC”。

如果我显示“BluetoohScanVC”并按下主页按钮,一切都按计划进行,一旦UUID到达,设备就会连接。但是当我显示另一个ViewController(即“FirstVC”)时,我无法运行它。

我试图在AppDelegate中调用BluetoothScanVC()。viewdidload() - applicationDidEnterBackground但没有成功。

我无法弄清楚如何在BluetoothScanVC中调用/运行此功能:

func centralManager(_ central:CBCentralManager,didDiscover peripheral:CBPeripheral,advertisementData:[String:Any],rssi RSSI:NSNumber)...

关闭应用程序并在之前显示另一个VC。

1 个答案:

答案 0 :(得分:0)

用于检测这些蓝牙设备的功能不应该存在于单个ViewController中,因为它将被解除分配。如果你想在应用程序的任何地方或后台发生某些事情,你应该检查出可能创建一个在AppDelegate中调用的单例,或者只是在AppDelegate中放置扫描蓝牙设备的代码。

您的AppDelegate可能如下所示:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  beginScanningForDevices()
  return true
}

func beginScanningForDevices() {
  // Code to scan for bluetooth devices
}
相关问题