无法通过CBCentral Manager扫描iBecon信号的服务ID

时间:2017-01-27 17:36:20

标签: ios bluetooth-lowenergy core-bluetooth cbperipheral cbcentralmanager

使用Core Bluetooth处理iBecon信号我可以使用CBCentralManager扫描选项搜索nil: -

Shared.sharedInstance.centralManager?.scanForPeripherals(withServices: nil, options:[CBCentralManagerScanOptionAllowDuplicatesKey:true])

但是当我提供我想要的服务ID时,即: -

Shared.sharedInstance.centralManager?.scanForPeripherals(withServices: [serviceID], options:[CBCentralManagerScanOptionAllowDuplicatesKey:true])

它永远不会调用didDiscoverPeripheral Delegate方法,我也需要在后台模式下扫描外设,根据Apple文档,您需要在后台模式下扫描时明确提供服务ID。任何人都可以帮助我在这里做错了。

1 个答案:

答案 0 :(得分:2)

我这样用, 连接按钮点击事件 并使用CBCentralManagerDelegate, CBPeripheralDelegate代表

func connectDevice(sender:UIButton){


                if peripheral != nil {
                    manager.cancelPeripheralConnection(peripheral)
                    manager = CBCentralManager(delegate: self, queue: nil)
                }
        }



 func centralManagerDidUpdateState(central: CBCentralManager) {
        if central.state == CBCentralManagerState.PoweredOn {
            central.scanForPeripheralsWithServices(nil, options: nil)
        } else {
            self.showAlert(Messages().alert , message: "Bluetooth is not on.")
        }
    }



 func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
        let device = (advertisementData as NSDictionary).objectForKey(CBAdvertisementDataLocalNameKey) as? NSString
        print(device)

        if device?.containsString(BEAN_NAME) == true {
            self.manager.stopScan()
            self.peripheral = peripheral
            self.peripheral.delegate = self
            manager.connectPeripheral(peripheral, options: nil)
        }
    }