使用Core Bluetooth处理iBecon信号我能够使用CBCentralManager扫描选项搜索nil: –
@H_301_2@Shared.sharedInstance.centralManager?.scanForPeripherals(withServices: nil,options:[CBCentralManagerScanOptionAllowDuplicatesKey:true])
但是,当我提供我理想的服务ID,即: –
@H_301_2@Shared.sharedInstance.centralManager?.scanForPeripherals(withServices: [serviceID],options:[CBCentralManagerScanOptionAllowDuplicatesKey:true])它从不调用didDiscoverPeripheral Delegate方法,我也需要在后台模式下扫描外设,并且根据Apple文档,您需要在需要在后台模式下扫描时明确提供服务ID.任何人都可以帮助我在这里做错事.
解决方法
我这样用,
连接按钮单击事件
并使用CBCentralManagerDelegate,CBPeripheralDelegate Delegate @H_301_2@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) } }
连接按钮单击事件
并使用CBCentralManagerDelegate,CBPeripheralDelegate Delegate @H_301_2@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) } }