iOS蓝牙4.0开发
原文链接:http://www.jianshu.com/p/974d165f78b5
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
iOS 蓝牙4.0开发
背景:
1.iOS的蓝牙不能用来传输文件。
2.iOS与iOS设备之间进行数据通信,使用gameKit.framework
3.iOS与其他非iOS设备进行数据通信,使用coreBluetooth.framework
iOS中蓝牙的实现方案
iOS中提供了4个框架用于实现蓝牙连接
GameKit.framework(用法简单)
只能用于iOS设备之间的连接,多用于游戏(比如五子棋对战),从iOS7开始过期
MultipeerConnectivity.framework
只能用于iOS设备之间的连接,从iOS7开始引入,主要用于文件共享(仅限于沙盒的文件)
ExternalAccessory.framework
可用于第三方蓝牙设备交互,但是蓝牙设备必须经过苹果MFi认证(国内较少)
CoreBluetooth.framework(时下热门)
可用于第三方蓝牙设备交互,必须要支持蓝牙4.0
硬件至少是4s,系统至少是iOS6
蓝牙4.0以低功耗著称,一般也叫BLE(BluetoothLowEnergy)
目前应用比较多的案例:运动手坏、嵌入式设备、智能家居
下面具体介绍使用CoreBluetooth.framework的代码步骤:
//蓝牙系统库
#import <CoreBluetooth/CoreBluetooth.h>
//必须要由UUID来唯一标示对应的service和characteristic
#define kServiceUUID @"5C476471-1109-4EBE-A826-45B4F9D74FB9"
#define kCharacteristicHeartRateUUID @"82C7AC0F-6113-4EC9-92D1-5EEF44571398"
#define kCharacteristicBodyLocationUUID @"537B5FD6-1889-4041-9C35-F6949D1CA034"
@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic,strong)CBCentralManager * centralManager;
@property (nonatomic,strong)CBPeripheral     * peripheral;
@end1.创建中心角色
#import <CoreBluetooth/CoreBluetooth.h>
- (void)viewDidLoad
{
    [super viewDidLoad];
    //初始化蓝牙 central manager
    _centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) options:nil];    
}2.扫描外设
[manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];3.连接外设
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
        if([peripheral.name  isEqualToString:BLE_SERVICE_NAME]){
                [self connect:peripheral];
        }
s);
}       
-(BOOL)connect:(CBPeripheral *)peripheral{
        self.manager.delegate = self;
        [self.manager connectPeripheral:peripheral
                                options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
}4.扫描外设中的服务和特征
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{ 
    NSLog(@"Did connect to peripheral: %@", peripheral);
    _testPeripheral = peripheral; 
    [peripheral setDelegate:self];  <br>//查找服务
    [peripheral discoverServices:nil]; 
}发现服务:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{ 
    NSLog(@"didDiscoverServices"); 
    if (error)
    {
        NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]); 
        if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)])
            [self.delegate DidNotifyFailConnectService:nil withPeripheral:nil error:nil]; 
        return;
    } 
    for (CBService *service in peripheral.services)
    {
         //发现服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]])
        {
            NSLog(@"Service found with UUID: %@", service.UUID);  <br>//查找特征
            [peripheral discoverCharacteristics:nil forService:service];
            break;
        } 
    }
}发现服务中的特征:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    if (error)
    {
        NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        [self error];
        return;
    }
    NSLog(@"服务:%@",service.UUID);
    for (CBCharacteristic *characteristic in service.characteristics)
    {
       //发现特征
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"xxxxxxx"]]) {
                NSLog(@"监听:%@",characteristic);<br>//监听特征
                [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
    }
}5.与外设进行数据交互
读取数据:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error)
    {
        NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);
        self.error_b = BluetoothError_System;
        [self error];
        return;
    }
//    NSLog(@"收到的数据:%@",characteristic.value);
    [self decodeData:characteristic.value];
}写数据:
NSData *d2 = [[PBABluetoothDecode sharedManager] HexStringToNSData:@"0x02"];
                [self.peripheral writeValue:d2 forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];iOS蓝牙4.0开发的更多相关文章
- iOS 蓝牙4.0开发
		背景: 1.iOS的蓝牙不能用来传输文件.2.iOS与iOS设备之间进行数据通信,使用gameKit.framework3.iOS与其他非iOS设备进行数据通信,使用coreBluetooth.fra ... 
- iOS蓝牙4.0开发(BLE)
		智能设备 和 app 通过 BLE通讯的两种模型 模型一:设备提供数据,app 展示数据: 比如小米手环 模型二:app提供数据,设备接收: 模型与corebluetooth的对应关系: 模型一:智能 ... 
- iOS蓝牙4.0开发例子
		1建立中心角色 1 2 3 #import <CoreBluetooth/CoreBluetooth.h> CBCentralManager *manager; manager = [ ... 
- iOS蓝牙BLE4.0通信功能
		概述 iOS蓝牙BLE4.0通信功能,最近刚学的苹果,为了实现蓝牙门锁的项目,找了一天学习了下蓝牙的原理,亲手测试了一次蓝牙的通信功能,结果成功了,那么就把我学习的东西分享一下. 详细 代码下载:ht ... 
- iOS蓝牙4.0协议简单介绍
		iOS开发蓝牙4.0的框架是CoreBluetooth,本文主要介绍CoreBluetooth的使用,关于本文中的代码片段大多来自github上的一个demo,地址是myz1104/Bluetooth ... 
- https://github.com/coolnameismy/BabyBluetooth  github上的一个ios 蓝牙4.0的库并带文档和教程
		The easiest way to use Bluetooth (BLE )in ios,even bady can use. 简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和 ... 
- iOS蓝牙4.0
		iOS的蓝牙用到了 CoreBluetooth 框架 首先导入框架 #import <CoreBluetooth/CoreBluetooth.h> 我们需要一个管理者来管理蓝牙设备,CB ... 
- android 蓝牙4.0 开发介绍
		最近一直在研究一个蓝牙功能 由于本人是菜鸟 学起来比较忙 一直搞了好久才弄懂 , 网上对蓝牙4.0也就是几个个dome 抄来抄去,全是英文注解 , 对英语不好的朋友来说 真是硬伤 , 一些没必要的描 ... 
- CoreBluetooth——IOS蓝牙4.0使用心得
		原文链接:http://m.blog.csdn.net/article/details?plg_nld=1&id=51014318&plg_auth=1&plg_uin=1&a ... 
随机推荐
- Struts初学
			自我概述 今天看了Struts,感觉这是个非常好用的东西!虽然它已经过时了,被springMVC取代了,但是仍然有了解的价值. 可是在学习过程中遇到了很多问题,比如其中一些原理很是抽象,有一些问题莫名 ... 
- python3笔记七:break和continue语句
			一:学习内容 break语句 continue语句 二:break语句 1. 说明 作用:跳出for和while的循环注意:只能跳出距离它最近的那一层循环 2.举例1 for i in range(1 ... 
- scrum例会报告+燃尽图01
			此作业要求参见:https://edu.cnblogs.com/campus/nenu/2019fall/homework/9954 一.小组情况 组长:贺敬文组员:彭思雨 王志文 位军营 徐丽君队名 ... 
- Python学习笔记:第一次接触
			用的是windows的IDLE(python 3) 对象的认识:先创建一个list对象(用方括号) a = ['xieziyang','chenmanru'] a 对list中对象的引用 a[0] # ... 
- synchronized与Lock区别简单总结
			类别 synchronized Lock 存在层次 Java的关键字,在jvm层面上 是一个类 锁的释放 1.以获取锁的线程执行完同步代码,释放锁 2.线程执行发生异常,jvm会让线程释放锁 在fin ... 
- centos7.7下docker与k8s安装(DevOps三)
			1.系统配置 centos7.7 docker 1.13.1 centos7下安装docker:https://www.cnblogs.com/pu20065226/p/10536744.html 2 ... 
- 【翻译】WPF应用程序模块化开发快速入门(使用Prism+MEF)
			编译并运行快速入门 需要在VisualStudio 2010上运行此快速入门示例 代码下载:ModularityWithMef.zip 先重新生成解决方案 再按F5运行此示例 说明: 在此快速入门示例 ... 
- OpenStack 制作image,启动VM,无console log
			OpenStack image 制作官方文档:https://docs.openstack.org/image-guide/create-images-manually.html 如果通过制作的镜像启 ... 
- 阶段3 2.Spring_08.面向切面编程 AOP_9 spring基于注解的AOP配置
			复制依赖和改jar包方式 src下的都复制过来. 复制到新项目里了 bean.xml里面复制上面一行代码到下面.把aop改成context. 配置spring容器创建时要扫描的包 Service的配置 ... 
- Python 的 Collection 库
			Collections 是 Python 内建的一个集合模块,提供了许多额外的数据类型. namedtuple namedtuple 主要用来生成可以使用名称来访问元素的数据对象,通常用来增强代码的可 ... 
