码迷,mamicode.com
首页 > 移动开发 > 详细

iOS中的BLE开发流程

时间:2014-11-26 20:28:28      阅读:246      评论:0      收藏:0      [点我收藏+]

标签: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

 

iOS中的BLE开发流程

标签:blog   io   ar   os   sp   for   strong   文件   on   

原文地址:http://www.cnblogs.com/dream-corner/p/4124036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!