下面是两台iPhone6连接同一台蓝牙设备的结果:

**成功连接**** peripheral: <CBPeripheral: 0x1700f4500, identifier = 50084F69-BA5A-34AC-8A6E-6F0CEADB21CD, name = 555555555588,
state = connected> with UUID: <__NSConcreteUUID 0x17003d980> 50084F69-BA5A-34AC-8A6E-6F0CEADB21CD**
****
****
**成功连接**** peripheral: <CBPeripheral: 0x1742e3000, identifier = 55B7D759-0F1E-6271-EA14-BC5A9C9EEEEC, name = 555555555588,
state = connected> with UUID: <__NSConcreteUUID 0x174036c00> 55B7D759-0F1E-6271-EA14-BC5A9C9EEEEC**

iOS的蓝牙开发很简单,只要包含一个库,创建CBCentralManager实例,实现代理方法,然后就可以直接和设备进行通信。

发现附近的特定蓝牙设备

#import <CoreBluetooth/CoreBluetooth.h>

首先可以定义一些即将使用到的UUID的宏


#define kPeripheralName     @"360qws Electric Bike Service" //外围设备名称
#define kServiceUUID        @"7CACEB8B-DFC4-4A40-A942-AAD653D174DC" //服务的UUID

#define kCharacteristicUUID @"282A67B2-8DAB-4577-A42F-C4871A3EEC4F" //特征的UUID
如果不是把手机作为中心设备的话,这些没有必要设置。

1.设备的UUID以及characteristic,可以把他们写成宏

#define TRANSFER_SERVICE_UUID           @"0000fff0-0000-1000-8000-00206f9c56cad"

#define TRANSFER_CHARACTERISTIC_UUID    @"0000fff7-0000-1000-8000-00806f9c56cad"

2.在.h文件中导入两个头文件,并在接口中实现两个协议

#import"ViewController.h"

#import<CoreBluetooth/CoreBluetooth.h>

//需要实现协议

@interfaceViewController () <CBCentralManagerDelegate,CBPeripheralDelegate>{}

3.创建两个蓝牙设备属性,一个相当于主机,一个相当于外设从机

#pragma mark
蓝牙设备

@property (strong,nonatomic)CBCentralManager   *centralManager;
       //接收

@property (strong,nonatomic)CBPeripheral       *discoveredPeripheral;
 //外设

@end

4.开始蓝牙配置

#pragma mark  在初始化界面结束后设置自己为代理

@implementation ViewController

- (void)viewDidLoad {

[superviewDidLoad];

_centralManager = [[CBCentralManageralloc]initWithDelegate:selfqueue:nil];

}

#pragma mark  此处监控一下central的状态值,可以判断蓝牙是否开启/可用

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

{

NSMutableString *stringForCentralManagerState = [NSMutableStringstringWithString:@"UpdateState:"];

switch (central.state) {

caseCBCentralManagerStateUnknown:

[stringForCentralManagerStateappendString:@"Unkown\n"];

break;

caseCBCentralManagerStateUnsupported:

[stringForCentralManagerStateappendString:@"Unsupported\n"];

caseCBCentralManagerStateUnauthorized:

[stringForCentralManagerStateappendString:@"Unauthorized\n"];

caseCBCentralManagerStateResetting:

[stringForCentralManagerStateappendString:@"Resetting\n"];

caseCBCentralManagerStatePoweredOff:

[stringForCentralManagerStateappendString:@"PowerOff\n"];

caseCBCentralManagerStatePoweredOn:

//设备支持BLE并且可用

[stringForCentralManagerStateappendString:@"PoweredOn\n"];

//开始搜索

[selfscan];

break;

default:

[stringForCentralManagerStateappendString:@"none\n"];

break;

}

NSLog(@"%@", stringForCentralManagerState);

}

#pragma mark
扫描

- (void)scan

{           [self.centralManage scanForPeripheralsWithServices:@[[CBUUI UUIDWithString:TRANSFER_SERVICE_UUID]]

options:@{CBCentralManagerScanOptionAllowDuplicatesKey
:@YES}];

NSLog(@"Scanning started");

}

#pragma mark
发现设备,连接

//一旦符合要求的设备被发现,就会回调此方法

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

{

NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);

if (self.discoveredPeripheral != peripheral) {

self.discoveredPeripheral = peripheral;

// 连接

[self.centralManagerconnectPeripheral:peripheraloptions:nil];

NSLog(@"Connecting to peripheral
%@", peripheral);

}

}

#pragma mark
未能连接的处理方法

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

{

NSLog(@"Failed to connect to %@. (%@)", peripheral, [errorlocalizedDescription]);

}


#pragma mark
当连接上设备

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

{

NSLog(@"Peripheral Connected");

//已连接上设备,故停止搜索

[self.centralManagerstopScan];

NSLog(@"Scanning stopped");

peripheral.delegate =self;

//寻找指定UUID的Service

[peripheraldiscoverServices:@[[CBUUIDUUIDWithString:TRANSFER_SERVICE_UUID]]];

}

#pragma mark
发现设备上指定Service会回调此处

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error

{

if (error) {

NSLog(@"Error discovering services: %@", [errorlocalizedDescription]);

return;

}

//寻找指定UUID的Characteristic

for (CBService *servicein peripheral.services) {

[peripheraldiscoverCharacteristics:@[[CBUUIDUUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]

forService:service];

}

}

#pragma mark
找到指定UUID的Characteristic会回调此处

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

{

if (error) {

NSLog(@"Error discovering characteristics: %@", [errorlocalizedDescription]);

return;

}

for (CBCharacteristic *characteristicin service.characteristics) {

if ([characteristic.UUIDisEqual:[CBUUIDUUIDWithString:TRANSFER_CHARACTERISTIC_UUID]])
{

NSLog(@"find the characteristic");

[peripheralsetNotifyValue:YESforCharacteristic:characteristic];

}

}

}

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

{

if (error) {

NSLog(@"Error discovering characteristics: %@", [errorlocalizedDescription]);

return;

}

NSLog(@"value --> %@",characteristic.value);

#pragma mark
把接收到的数据进行截取

//此处我们就可以拿到value值对其进行数据解析了

NSData *data = characteristic.value;

}

#pragma mark
蓝牙断开后自动重连

-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral
error:(NSError *)error

{

NSLog(@"Peripheral Disconnected");

self.discoveredPeripheral =nil;

// 重新开启搜索

[selfscan];

UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"蓝牙连接状态"message:@"连接已断开"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:@"关闭",nil];

[alert
show];

}

5.蓝牙后台运行

若要实现蓝牙4.0在APP进入后台时仍能工作,传输数据,不用写代码,只需要修改xxx-info.plist文件即可
在Required background modes中加入两项
App shares data using CoreBluetooth  和  App communicates using CoreBluetooth
即可

iOS关于蓝牙连接的简单介绍与使用的更多相关文章

  1. iOS开发数据库篇—SQLite简单介绍

    iOS开发数据库篇—SQLite简单介绍 一.离线缓存 在项目开发中,通常都需要对数据进行离线缓存的处理,如新闻数据的离线缓存等. 说明:离线缓存一般都是把数据保存到项目的沙盒中.有以下几种方式 (1 ...

  2. iOS开发数据库篇—FMDB简单介绍

    iOS开发数据库篇—FMDB简单介绍 一.简单说明 1.什么是FMDB FMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API 2.FMDB的优点 使用起来 ...

  3. iOS开发拓展篇-XMPP简单介绍

    iOS开发拓展篇-XMPP简单介绍 一.即时通讯简单介绍 1.简单说明 即时通讯技术(IM)支持用户在线实时交谈.如果要发送一条信息,用户需要打开一个小窗口,以便让用户及其朋友在其中输入信息并让交谈双 ...

  4. 【转】 iOS开发数据库篇—SQLite简单介绍

    开始学SQLite啦, 原文: http://www.cnblogs.com/wendingding/p/3868893.html iOS开发数据库篇—SQLite简单介绍 一.离线缓存 在项目开发中 ...

  5. iOS开发多线程篇—多线程简单介绍

    iOS开发多线程篇—多线程简单介绍 一.进程和线程 1.什么是进程 进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开QQ.Xcod ...

  6. iOS开发UI篇—UITabBarController简单介绍

    iOS开发UI篇—UITabBarController简单介绍 一.简单介绍 UITabBarController和UINavigationController类似,UITabBarControlle ...

  7. iOS开发UI篇—Modal简单介绍

    iOS开发UI篇—Modal简单介绍 一.简单介绍 除了push之外,还有另外一种控制器的切换方式,那就是Modal 任何控制器都能通过Modal的形式展⽰出来 Modal的默认效果:新控制器从屏幕的 ...

  8. iOS开发UI篇—Kvc简单介绍

    ios开发UI篇—Kvc简单介绍 一.KVC简单介绍 KVC key valued coding 键值编码 KVC通过键值间接编码 补充: 与KVC相对的时KVO,即key valued observ ...

  9. iOS开发UI篇—UIWindow简单介绍

    iOS开发UI篇—UIWindow简单介绍 一.简单介绍 UIWindow是一种特殊的UIView,通常在一个app中只会有一个UIWindow iOS程序启动完毕后,创建的第一个视图控件就是UIWi ...

随机推荐

  1. 在ubuntu上搭建交叉编译环境---arm-none-eabi-gcc

    最近要开始搞新项目,基于arm的高通方案的项目. 那么,如何在ubuntu上搭建这个编译环境呢? 1.找到相关的安装包:http://download.csdn.net/download/storea ...

  2. tolua++没法用

    tolua++没法用(金庆的专栏)觉得从C++头文件生成lua绑定代码的方法比较简单,想试试tolua++.从Github获取toluapp:https://github.com/LuaDist/to ...

  3. java学习路线图-----java基础学习路线图(J2SE学习路线图)

    安装JDK和开发软件跳过,网上太多了,不做总结,以下是我总结的学习路线图,欢迎补充. JAVA基础语法 注释,标识符命名规则及Java中的关键字 Java基本数据类型 Java运算符与表达式 Java ...

  4. Dynamics CRM2015 Update1 新功能之表单增强功能

    CRM2015 Update 1发布后,系统的界面的变化很大,仔细观察后会发现表单窗体也有些不同了,在CRM2015 Update1的官方介绍中对此变化的解释是起用了新的窗体呈现引擎,让界面更好看加载 ...

  5. Swift基础之对FMDB第三方的使用方法

    相信大家都熟悉OC使用FMDB第三方库,进行数据库操作,增.删.改.查,现在我就来利用代码展示一下Swift对此库的使用方法,我是通过Pods添加的第三方库,如果手动添加记得创建桥接文件,在文件中调用 ...

  6. SpringMVC实现用户登录实例

    今天分享一下SpringMVC的一个登陆小案例 准备工作 创建一个Dynamic Web Project(本人是Eclipse) 添加相关的jar包,构建路径 创建springMVC-servlet. ...

  7. Xcode中为何要为设置bundle和App分别设置两份一样的图片资源

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 我们知道在App设置的bundle中有时也会用到图片资源,而在 ...

  8. Hibernate之多对多表,操作实例

    多表操作之多对多关系简介 思路就是: 在数据库底层通过添加中间表来指定关联关系. 在双方的实体中添加一个保存对方的集合 在双方的配置文件中使用set标签和many-to-many标签来进行关联关系的配 ...

  9. EBS密码加密研究

     DECLARE   v_password_1 VARCHAR2(240);   v_password_2 VARCHAR2(240);   v_password_3 VARCHAR2(240); ...

  10. 07_NoSQL数据库之Redis数据库:Redis的高级应用之事务处理、持久化操作、pub_sub、虚拟内存

     事务处理 Redis对事务的支持目前还比较简单.Redis只能保证一个client发起的事务中的命令可以连续的执行,而中间不会插入其他client的命令.当一个client在一个连接中发出mul ...