标签:blog io ar os sp for strong 文件 on
// // ViewController.m // BLEEx2 // // Created by 我的未来不是梦 on 14-11-26. // Copyright (c) 2014年 choicemmed. All rights reserved. // #import "ViewController.h" // 1 导头文件 #import <CoreBluetooth/CoreBluetooth.h> @interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>
@property(nonatomic, strong) CBCentralManager *mgr; @property(nonatomic, strong) NSMutableArray *peripherals;
@end @implementation ViewController - (NSMutableArray *)peripherals{ if (!_peripherals) { _peripherals = [NSMutableArray array]; } return _peripherals; } - (void)viewDidLoad {
[super viewDidLoad]; // 2 创建 中心管理者对象 CBCentralManager *mgr = [[CBCentralManager alloc] init]; mgr.delegate = self; self.mgr = mgr; // 3 扫描外设 参数传nil 表示搜索所有外设 [mgr scanForPeripheralsWithServices:nil options:nil]; } // 模拟连接外设 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 扫描外设中的服务和特征 for (CBPeripheral *peripheral in self.peripherals) { peripheral.delegate = self;
// 利用mgr 连接外设 [self.mgr connectPeripheral:peripheral options:nil]; } } #pragma mark - CBCentralManagerDelegate // 中心管理 扫描到外设 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { // 将外设保存 if (![self.peripherals containsObject:peripheral]) { [self.peripherals addObject:peripheral]; } } // 中心管理 连接外设成功 (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { // 扫描外设中的服务 [peripheral discoverServices:nil]; } // 中心管理 连接外设失败 - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { NSLog(@"%@",error); } #pragma mark - CBPeripheralDelegate // 外设扫描到服务 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { NSArray *services = peripheral.services; for (CBService *service in services) { // 取得需要的服务 if ([@"needService" isEqualToString:service.UUID.UUIDString]) { [peripheral discoverCharacteristics:nil forService:service]; } } } - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { NSArray *characteristics = service.characteristics; for (CBCharacteristic *characteristic in characteristics) { if ([@"needCharacteristic" isEqualToString:characteristic.UUID.UUIDString]) { NSLog(@"do somthing~"); } } } @end
标签:blog io ar os sp for strong 文件 on
原文地址:http://www.cnblogs.com/dream-corner/p/4124036.html