iOS-蓝牙-后台重连

简单记录一下:
前提条件是已经可以在后台时收发蓝牙数据。
在后台断开连接时,程序确实调用了:

central.scanForPeripheralsWithServices(nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])

但是一直无法扫描到我需要连接的设备,在网上找原因,发现一个网站是这样描述的:

When backgrounding, you can still scan and connect to a LE peripheral. You can scan for peripherals using scanForPeripheralsWithSerives by stating what service you are looking for in a Peripheral. You cannot do a general scan without stating at least one service in the passed dictionary. If you have a CFUUIDRef from a previous connection, you can call retrievePeripherals with the CFUUIDRef. Your delegate will receive a call to didRetrievePeripherals with a CBPeripheral. With the CBPeripheral you can then connect using connectPeripheral.

大意如下:
程序在后台时,依然可以扫描并且连接蓝牙设备。我们可以用『scanForPeripheralsWithSerives』去扫描一个指定的设备(传入特定的serviceUUIDs参数),不可以传nil扫描周围所有的设备,如果传nil,我们无法扫描到周围的任何设备。
当我把代码改成如下:

let uuid = CBUUID.init(string:ServicesUUID)
central.scanForPeripheralsWithServices([uuid], options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])

程序就可以在后台重连蓝牙设备了。

你可能感兴趣的:(iOS-蓝牙-后台重连)