iOS中蓝牙的使用

  Core Bluetooth的使用

 1,建立中心设备

 2,扫描外设(Discover Peripheral)

 3,连接外设(Connect Peripheral)

 4,扫描外设中的服务和特征(Discover Services And Characteristics)

 5,利用特征与外设做数据交互(Explore And Interact)

 6,断开连接(Disconnect)

//  ViewController.m

//  01-蓝牙4.0

//  Created by apple on 16/1/4.

//  Copyright © 2016年 apple. All rights reserved.

 #import "ViewController.h"

#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (nonatomic,strong)CBCentralManager *manager;

@property (nonatomic,strong)NSMutableArray *peripherals;//盛放外围设备的数组

@end

@implementation ViewController

- (NSMutableArray *)peripherals

{

    if (_peripherals == nil) {

        

        _peripherals = [NSMutableArray array];

    }

    return _peripherals;

}

- (void)viewDidLoad {

    [super viewDidLoad];

    //1.创建中心管理者

    //传 nil 为主队列

    CBCentralManager *manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];

    self.manager = manager;

}

 //状态发生改变的时候  回来到此方法

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

{

 //2.先判断蓝牙是打开

      if (central.state == CBCentralManagerStatePoweredOn) {

         //3.搜索外围设备

          [central scanForPeripheralsWithServices:nil options:nil];

    }

   }

 //CBPeripheral 外围设备

//advertisementData配置信息

//RSSI  信号强度

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI

{

    [self.peripherals addObject:peripheral];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    //4.连接外围设备

    //遍历数组

     for (int i = 0; i < self.peripherals.count; i ++) {

        CBPeripheral *peripheral = self.peripherals[i];

         [self.manager connectPeripheral:peripheral options:nil];

    }

 }

 //连接外围设备之后  会来到此方法

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

{

//5.获取服务

     [peripheral  discoverServices:nil];

    peripheral.delegate = self;

}

//发现服务会来的此方法

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

{

  //6.通过服务去找特征

 [peripheral  discoverCharacteristics:nil forService:peripheral.services.lastObject];

}

//发现特征会来的此方法

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

{

 }

 @end

原文地址:https://www.cnblogs.com/peteremperor/p/5263263.html