The recent project is mainly about bluetooth connection and communication between iPhone and some common devices. So I sorted out some knowledge of Bluetooth.

There are two main approaches to iOS Bluetooth development.

Gamekit. framework bluetooth communication framework prior to iOS7. It has been out of date since iOS7, but most apps are still based on this framework. Can only be used between iOS devices, mostly for games.

2 MultipeerConnectivity. Framework iOS7 began to introduce the new bluetooth communication development framework, is used to replace GameKit. It can be used only between iOS devices to share files.

Corebluetooth. framework is a powerful Bluetooth development framework that requires devices to support Bluetooth 4.0 and communicate with other third-party devices.

4 ExternalAccessory. Bluetooth equipment interaction framework can also be used with third parties, but the bluetooth device must undergo MFI certification, requires apple’s agreement, it has some limitations.

CoreBluetooth is not limited to transferring data between iOS devices. You can transfer data between iOS devices to Android, Windows Phone, and other smart devices with Bluetooth 4.0 chips. Therefore, it is also the technology respected by smart home, wireless payment and other popular smart devices. So let me show you how to use this.

CoreBluetooth.framework

Apple has introduced this framework since iOS6, which is specifically designed to communicate with BLE4.0 devices, not just iOS devices.

The core of the CoreBluetooth framework is actually two things, peripheral and central, which can be understood as peripherals and centers. Similar to the C/S design (client and server), peripherals can be understood as clients and central devices as servers.

Peripheral and central devices are represented in CoreBluetooth using CBPeripheralManager and CBCentralManager.

CBPeripheralManager: Peripherals are typically used to publish services, generate data, and store data. Peripheral devices publish and broadcast services, telling surrounding central devices about its available services and features.

CBCentralManager: Central devices use peripheral data. The central device scans the peripherals and attempts to establish a connection. Once the connection is successful, these services and features can be used.

The Bridges between peripheral and central devices are services (CBServices) and characteristics (CBCharacteristic), each of which has a unique identifier UUID (CBUUID type) to uniquely identify a service or characteristic. Each service can have multiple characteristics.

The central device is on the left and the peripheral device is on the right.

CBCentralManager Central device management, using data from peripheral devices. The central device scans the peripherals and attempts to establish a connection. Once the connection is successful, these services and features can be used.

CBPeripheralManager peripheral device management, typically used to publish services, generate data, and save data. Peripheral devices publish and broadcast services, telling surrounding central devices about its available services and features.

CBPeripheral peripheral.

CBCentral Central equipment.

CBService and CBMutableServic services, in which CBMutableServic is a subclass of CBService, only one more initialization method and two variables.

CBCharacteristic and CBMutableCharacteristic. CBMutableCharacteristic is a subclass of CBCharacteristic, with an initialization method and several variables. CBUUID UUID help class.

A read or write request issued by the CBATTRequest central.

Mainly talk about the use of central equipment.

Bluetooth in the iOS operating mainly in BluetoothManager/GABluetoothManager class. The class follow < CBCentralManagerDelegate CBPeripheralDelegate > agreement.

Methods in CBCentralManagerDelegate have central availability, scanned peripherals, and connection status with peripherals.

CBPeripheralDelegate is mainly for discovering services, features, descriptions, read and write features, and descriptions.

Initialize the central manager

self.cbCM = [[CBCentralManager alloc] init];
self.cbCM.delegate = self;
Copy the code

Scanning peripheral

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO],CBCentralManagerScanOptionAllowDuplicatesKey, nil];
self.cbCM scanForPeripheralsWithServices:nil options:dic];
Copy the code

ScanForPeripheralsWithServices method

The first argument is that you want to scan peripherals that specify the UUID service. Nil is to scan all.

The second parameter scan option,

CBCentralManagerScanOptionAllowDuplicatesKey when specifying its to YES, filter function is not enabled, that is to say, centra every time can receive the broadcast packet data from peripherals, This can have a significant impact on battery life. When set to NO it merges the same peripheral every time it looks.

/ * *

  • Discovering peripherals

  • @Param Central Center management

  • @Param Peripheral peripheral

  • @param advertisementData Broadcasts data

  • Param RSSI Signal quality (signal strength)

* /

  • (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI

The name in the test peripheral parameter cannot be guaranteed to be the latest name (when a peripheral changes the Bluetooth name), so we use data from the broadcast

AdvertismentData, the data in the broadcast is up to date and can be broadcast by the Bluetooth name and uUID of the service.

[self.cbCM stopScan]; // Stop scanning

Connecting peripherals

[self.cbCM connectPeripheral:device.peripheral
    options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
Copy the code

In options, you can set some initial property keys for connected devices as follows

NSString *const CBConnectPeripheralOptionNotifyOnConnectionKey;

When the APP is suspended, if the APP is connected to the peripheral, should a prompt box be given to the APP, of course, at the early stage when the APP supports background operation?

NSString *const CBConnectPeripheralOptionNotifyOnDisconnectionKey;

When the APP is in the suspended state, it is exactly at this time to disconnect, should I give the APP a disconnect prompt? This case is only displayed if the APP is specified to run in the background.

NSString *const CBConnectPeripheralOptionNotifyOnNotificationKey;

When the App is in the suspended state, a prompt box will pop up whether all peripheral packages are received or not. Of course, this key value is also prior to the APP can run in the background. // Failed to connect the peripheral

  • (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

// Connect to the peripheral

  • (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

Discover services, features, and descriptions

After the connection is successful, services are found

It is important to set the peripheral delegate to self; otherwise, didDiscoverServices cannot call back

peripheral.delegate = self;

[peripheral discoverServices:nil]; Parameter specifies the service UUID. Nil does not limit the UUID. // Services have been found

  • (void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error verifies that the service uuid is the desired uuid and if it is, the feature is found.

[peripheral discoverCharacteristics:nil forService:service]; You can specify the CHARACTERISTIC Uuid. // Characteristics are found

  • (void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

Verify that the characteristic UUID is correct. If it is correct, send data and subscribe characteristics.

communication

After verifying characteristic correctness, subscribe to this characteristic [Peripheral setNotifyValue:YES forCharacteristic:c]. The following method is called when the characteristic value changes:

  • (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic Error :(NSError *)error then sends data to the peripheral. NSString *str = [NSString stringWithFormat:@”<%@>%@”, (hasbond ? @”connect” : @”bind”), self.myUUID]; NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding]; [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse]; Parameter CBCharacteristicWriteWithResponse, requires the peripheral equipment to respond to the write request.

Here is the end of the article, you can also be a private letter I timely accessThe iOS developmentAnd information about the interview. If you have any comments and suggestions, please leave a message to me.

IOS partners please pay attention to! If you like, give a thumbs-up! Thank you very much! Thank you very much! thank you

Click to get:IOS Interview Materials

The original link: blog.csdn.net/VNanyeshesh…