在后台iOS Swift中扫描附近的所有蓝牙设备

时间:2018-05-17 10:58:39

标签: ios swift bluetooth-lowenergy core-bluetooth

我正在尝试扫描背景中附近的所有设备,只要应用程序进入后台,扫描过程就会停止。连接在前台运行良好。

我尝试在info.plist中添加密钥。

<key>UIBackgroundModes</key>
   <array>
    <string>bluetooth-central</string>
    <string>bluetooth-peripheral</string>
</array>

下一步

if centralManager == nil
    {
        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
        centralManagerDidUpdateState(centralManager)
    }

代表方法:

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == CBManagerState.poweredOn {
        // We will just handle it the easy way here: if Bluetooth is on, proceed...start scan!
        print("Bluetooth Enabled")
        startScan()
        // Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.startScan), userInfo: nil, repeats: true)

    } else {
        //If Bluetooth is off, display a UI alert message saying "Bluetooth is not enable" and "Make sure that your bluetooth is turned on"
        print("Bluetooth Disabled- Make sure your Bluetooth is turned on")


    }
}

开始扫描方法

 @objc func startScan() {
    peripherals = []
    print("Now Scanning...")
    self.timer.invalidate()
    let options: NSDictionary = NSDictionary(objects: [NSNumber(value: false as Bool)], forKeys: [CBCentralManagerScanOptionAllowDuplicatesKey as NSCopying])
    centralManager?.scanForPeripherals(withServices: nil , options:  options as? [String : AnyObject])

}

1 个答案:

答案 0 :(得分:0)

有意无。 蓝牙中央和蓝牙外围设备需要与蓝牙配件建立连接。但是,只需一直扫描任何设备意味着你不应该继续使用电源。