The use and attention of iOS Bluetooth

Get into the habit of writing together! This is the first day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

Recently, I have used low-power bluetooth in the project, so I will write about the use of bluetooth and the problems encountered in its use. If there is any problem in the text, please correct me.

Generally, the main process of using Bluetooth is usually as follows:

  • Start a central management object
  • Discover and connect to advertised devices
  • Scan the data after connecting the device.
  • Send read and write requests for characteristics of device services
  • Subscription supports the feature of notified (actively reported when data is updated).

The properties and methods we commonly use are as follows:

CBCentralManager

The CBCentralManager object, the so-called central management object, is the CoreBluetooth object-oriented symbol of the local central device. The state of the current CBCentralManager object can be obtained through CBManagerState. as shown in the code below

public enum CBManagerState : Int {
    case unknown = 0    //未知
    case resetting = 1  //复位
    case unsupported = 2 //该设备不支持蓝牙
    case unauthorized = 3//该设备无权限使用蓝牙
    case poweredOff = 4  //蓝牙关闭
    case poweredOn = 5   //蓝牙打开
}
复制代码

initialization

There are two initialization methods for CBCentralManager

public convenience init(delegate: CBCentralManagerDelegate?, queue: DispatchQueue?)

@available(iOS 7.0, )
public init(delegate: CBCentralManagerDelegate?, queue: DispatchQueue?, options: [String : Any]? = nil)
复制代码

delegate: Set the proxy
queue: Indicate which queue to process the event in. When it is nil, it means that the main thread will process
options: This dictionary has two official keys
CBCentralManagerOptionShowPowerAlertKey: A warning box will pop up when the Bluetooth switch is not turned on
CBCentralManagerOptionRestoreIdentifierKey: The system uses this UID to Identify a specific
CentralManager. Therefore, in order to continue the execution of the application, the UID must remain unchanged for the CentralManager to recover successfully.

There are many proxy methods of commonly used CBCentralManagerDelegate and CBPeripheralDelegate. Only some of them are listed below.

The connection status update, you can use this proxy method to get whether the current device Bluetooth is available

func centralManagerDidUpdateState(_ central: CBCentralManager)
复制代码

Scan to discover devices

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

Note⚠️: When scanning and discovering devices, the iOS side cannot directly obtain the Bluetooth Mac address like Android. The Bluetooth Mac address of the iOS side is stored in advertisementData and needs to be further converted, which can be converted by the following methods

let _tempData = advertisementData["kCBAdvDataManufacturerData"]

let macAddress = "\(String(describing: _tempData))".substring(from: "<").substring(to: ">").replacingOccurrences(of: " ", with: "").uppercased().reversed(preserveFormat: false).substring(to: 12).reversed(preserveFormat: false)
复制代码

Bluetooth device is connected

func centralManager( _ central: CBCentralManager, didConnect peripheral: CBPeripheral)
复制代码

The connection to the Bluetooth device fails. You can print the error message to troubleshoot the cause of the failure.

func centralManager( _ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?)
复制代码

Bluetooth device has been disconnected

func centralManager( _ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?)
复制代码

The command is sent using the func writeValue( _ data: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType)method under CBPeripheral. The CBCharacteristicWriteType has two values, withResponse and withoutResponse. Some students send commands to Bluetooth, but the Bluetooth device does not respond. This value is wrong. Students who do not know which value to use, You can check with your fellow classmates.

The reading and parsing of Bluetooth data will not be elaborated here. In the final analysis, it is only the parsing of data packets and the reading of defined fields.

Guess you like

Origin juejin.im/post/7081641447702659085