In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "iOS how to develop Bluetooth connection and data read and write function", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "iOS how to develop Bluetooth connection and data read and write function" this article.
Before doing Bluetooth development, it is best to understand some concepts: services: there must be a service for Bluetooth peripherals to broadcast, and there may be more than one service. There are some features under the service, and the service can be understood as a window of a module. Characteristic: what exists under a service, there can also be multiple features under a service. Features can be understood as windows to achieve specific functions. Generally, features have value, that is, eigenvalues, and features are the smallest unit that interacts with the outside world. UUID: it can be understood as a unique identifier on Bluetooth (certainly not in hardware, but it is easy for us to develop). In order to distinguish different services and features, or to name services and features, we use UUID to represent services and features.
Bluetooth connection can be roughly divided into the following steps
1. Set up a Central Manager instance for Bluetooth management 2. Search peripherals 3. Connect peripherals 4. Get the service of peripheral equipment 5. Characteristics of access to services 6. Read data from peripherals 7. Send data to peripherals other: reminders
First of all, let's import the framework of the system's BLE # import
Must abide by 2 agreements
/ * * Central Manager * / @ property (nonatomic, strong) CBCentralManager * cMgr
/ * Peripheral connected to * / @ property (nonatomic, strong) CBPeripheral * peripheral
1. Set up a Central Manager instance for Bluetooth management
-(CBCentralManager *) cmgr {if (! _ cmgr) {_ cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];} return _ cMgr;} / / this agent method will be triggered to determine the Bluetooth status of the phone as soon as the central manager initializes-(void) centralManagerDidUpdateState: (CBCentralManager *) central {switch (central.state) {case 0: NSLog (@ "CBCentralManagerStateUnknown"); break; case 1: NSLog (@ "CBCentralManagerStateResetting"); break; case 2: NSLog (@ "CBCentralManagerStateUnsupported") / / Bluetooth break; case 3: NSLog (@ "CBCentralManagerStateUnauthorized") is not supported; break; case 4: {NSLog (@ "CBCentralManagerStatePoweredOff"); / / Bluetooth is not enabled} break; case 5: {NSLog (@ "CBCentralManagerStatePoweredOn"); / / Bluetooth is enabled / / perform some operations after the central manager has successfully enabled / / search for peripherals [self.cMgr scanForPeripheralsWithServices:nil / / filter peripherals through some services] / / dict, after the condition / / search is successful, call our proxy method / /-(void) centralManager: (CBCentralManager *) central didDiscoverPeripheral: (CBPeripheral *) peripheral advertisementData: (NSDictionary *) advertisementData RSSI: (NSNumber *) RSSI; / / find the peripheral} break; default: break;}}
two。 Search for peripherals (I use a bracelet around me for example)
/ / method called after the peripheral is found-(void) centralManager: (CBCentralManager *) central / / Central Manager didDiscoverPeripheral: (CBPeripheral *) peripheral / / Peripheral advertisementData: (NSDictionary *) advertisementData / / data carried by the Peripheral RSSI: (NSNumber *) RSSI / / Bluetooth signal strength {/ / NSLog (@ "% s, line =% d, cetral =% @, peripheral =% @, advertisementData =% @, RSSI =% @", _ _ FUNCTION__) _ _ LINE__, central, peripheral, advertisementData, RSSI) / * peripheral =, advertisementData = {kCBAdvDataChannel = 38; kCBAdvDataIsConnectable = 1; kCBAdvDataLocalName = OBand; kCBAdvDataManufacturerData =; kCBAdvDataServiceUUIDs = (FEE7); kCBAdvDataTxPowerLevel = 0;}, RSSI =-55 according to the print result, we can get a sports bracelet whose name is OBand-75 * / / need to filter / / 1 for the peripheral connected to. Signal strength (connection over 40, connection above 80) / / 2. Through the device name (the device string prefix is OBand) / / at this point our filtering rule is: there is an OBand prefix and the signal strength is greater than 35 / / by printing, we know that RSSI is generally if with-([peripheral.name hasPrefix:@ "OBand"]) {/ / do some processing on our advertisementData (broadcast data carried by peripherals) here / / usually by filtering, we get some peripherals Then store the peripherals in our variable array, / / since there is only one sports bracelet nearby, we first press one peripheral to process / / mark our peripherals so that their life cycle = vc self.peripheral = peripheral / / after discovery, connect [self.cMgr connectPeripheral:self.peripheral options:nil]; NSLog (@ "% s, line =% d", _ _ FUNCTION__, _ _ LINE__);}}
3. Connect peripherals
/ / Central Manager successfully connected peripherals-(void) centralManager: (CBCentralManager *) central / / Central Manager didConnectPeripheral: (CBPeripheral *) peripheral / / Peripheral {NSLog (@ "% s, line =% d,% @ = connected successfully", _ _ FUNCTION__, _ _ LINE__, peripheral.name); / / after successful connection, services and features can be discovered / / proxy self.peripheral.delegate of peripherals can be set = self / / Peripheral Discovery Service. Passing nil means not filtering / / the proxy method that triggers the peripheral here-(void) peripheral: (CBPeripheral *) peripheral didDiscoverServices: (NSError *) error [self.peripheral discoverServices:nil] } / / Peripheral connection failed-(void) centralManager: (CBCentralManager *) central didFailToConnectPeripheral: (CBPeripheral *) peripheral error: (NSError *) error {NSLog (@ "% s, line =% d,% @ = connection failed", _ _ FUNCTION__, _ _ LINE__, peripheral.name) } / / lost connection-(void) centralManager: (CBCentralManager *) central didDisconnectPeripheral: (CBPeripheral *) peripheral error: (NSError *) error {NSLog (@ "% s, line =% d,% @ = disconnect", _ _ FUNCTION__, _ _ LINE__, peripheral.name);}
4. Get the service of peripheral equipment & 5. Characteristics of access to services
/ / proxy method called when a feature is found in a peripheral service (this is an important method. Here you can find the feature you need by knowing UUID in advance, subscribe to the feature, or write data to the feature here)-(void) peripheral: (CBPeripheral *) peripheral didDiscoverCharacteristicsForService: (CBService *) service error: (NSError *) error {NSLog (@ "% s, line =% d", _ _ FUNCTION__, _ LINE__) For (CBCharacteristic * cha in service.characteristics) {/ / NSLog (@ "% s, line =% d, char =% @", _ _ FUNCTION__, _ LINE__, cha);}}
5. Read data from peripherals
/ / when you update the value of the feature (all data transmitted from Bluetooth will go through this callback, to put it simply, this method is the only way for you to get the data) you can determine whether-(void) peripheral: (CBPeripheral *) peripheral didUpdateValueForCharacteristic: (CBCharacteristic *) characteristic error: (NSError *) error {NSLog (@ "% s, line =% d", _ _ FUNCTION__, _ LINE__) If (characteristic = @ "the UUID of the feature you want or the feature you have found") {/ / characteristic.value is the data you want}}
6. Send data to the peripheral (that is, write data to Bluetooth)
You can put this method in the button response, or you can write it when you find the feature, depending on how your business requirements are used.
[self.peripherale writeValue:_batteryData forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse]; / / the first parameter is the connected Bluetooth device; the second parameter is which feature to write to; and the third parameter is whether the response record is successfully written.
/ / Note whether the attribute of the feature supports writing data-(void) yf_peripheral: (CBPeripheral *) peripheral didWriteData: (NSData *) data forCharacteristic: (nonnull CBCharacteristic *) characteristic {/ * typedef NS_OPTIONS (NSUInteger, CBCharacteristicProperties) {CBCharacteristicPropertyBroadcast = 0x01, CBCharacteristicPropertyRead = 0x02, CBCharacteristicPropertyWriteWithoutResponse = 0x04, CBCharacteristicPropertyWrite = 0x08, CBCharacteristicPropertyNotify = 0x10, CBCharacteristicPropertyIndicate = 0x20, CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40, CBCharacteristicPropertyExtendedProperties = 0x80, CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE (NA, 6 percent 0) = 0x100, CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE (NA, 6 percent 0) = 0x200} Print out the characteristics of the permission (characteristic.properties), you can see that there are many kinds, this is an enumeration of NS_OPTIONS, can be multiple values common and read,write,noitfy,indicate. Knowing that these are basically enough, the first two are read and write permissions, and the latter two are notifications. The two different notification methods are * / / NSLog (@ "% s, line =% d, char.pro =% d", _ _ FUNCTION__, _ _ LINE__, characteristic.properties); / at this time, because the enumeration property is NS_OPTIONS, so an enumeration may correspond to multiple types, so the judgment cannot use =, but should include &}.
The above is all the content of this article "how to develop Bluetooth connection and data read and write function in iOS". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 269
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.