原文链接:http://m.blog.csdn.net/article/details?plg_nld=1&id=51014318&plg_auth=1&plg_uin=1&plg_usr=1&plg_vkey=1&plg_nld=1&plg_d

文章出处http://blog.csdn.net/xgcyangguang

所做的东西是通过手机/pad与蓝牙4.0的设备进行连接,之后设备上按对应的按键我们会收到对应的数值。首先需要和做蓝牙4.0的同事沟通好通信协议,具体的数据解析部分就不过多赘述了,主要写一下蓝牙接收数据的部分



1.和做蓝牙的同事沟通好设备的UUID以及特点,可以把他们写成宏



#define TRANSFER_SERVICE_UUID           @"0000fff0-0000-1000-8000-00805f9b34fb"
#define TRANSFER_CHARACTERISTIC_UUID    @"0000fff7-0000-1000-8000-00805f9b34fb"

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



#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "UUID.h"

//需要实现协议
@interface ViewController () < CBCentralManagerDelegate, CBPeripheralDelegate>
{

}

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

#pragma mark 蓝牙设备
@property (strong, nonatomic) CBCentralManager      *centralManager;         //接收
@property (strong, nonatomic) CBPeripheral          *discoveredPeripheral;   //外设

@end
4.开始蓝牙配置
#pragma mark 在初始化界面结束后设置自己为代理
- (void)viewDidLoad {
    [super viewDidLoad];

   _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

#pragma mark 此处监控一下中央的状态值,可以判断蓝牙是否开启/可用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSMutableString *stringForCentralManagerState = [NSMutableString stringWithString:@"UpdateState:"];

    switch (central.state) {
        case CBCentralManagerStateUnknown:
            [stringForCentralManagerState appendString:@"Unkown\n"];
            break;
        case CBCentralManagerStateUnsupported:
            [stringForCentralManagerState appendString:@"Unsupported\n"];
        case CBCentralManagerStateUnauthorized:
            [stringForCentralManagerState appendString:@"Unauthorized\n"];
        case CBCentralManagerStateResetting:
            [stringForCentralManagerState appendString:@"Resetting\n"];
        case CBCentralManagerStatePoweredOff:
            [stringForCentralManagerState appendString:@"PowerOff\n"];
        case CBCentralManagerStatePoweredOn:
            //设备支持BLE并且可用
            [stringForCentralManagerState appendString:@"PoweredOn\n"];

            //开始搜索
            [self scan];
            break;
        default:
            [stringForCentralManagerState appendString:@"none\n"];
            break;
    }
    NSLog(@"%@", stringForCentralManagerState);

}

#pragma mark 扫描
- (void)scan
{

    //第一个参数如果设置为nil,会寻找所有service
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID 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;

        // 连接
        NSLog(@"Connecting to peripheral %@", peripheral);
        [self.centralManager connectPeripheral:peripheral options:nil];
    }
}

#pragma mark 未能连接的处理方法
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Failed to connect to %@. (%@)", peripheral, [error localizedDescription]);
//    [self cleanup];
}

#pragma mark 当连接上设备
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Peripheral Connected");

    // 已连接上设备,故停止搜索
    [self.centralManager stopScan];
    NSLog(@"Scanning stopped");
    // Make sure we get the discovery callbacks
    peripheral.delegate = self;

    // 寻找指定UUID的Service
    [peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
}

#pragma mark 发现设备上指定Service会回调此处
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error) {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        return;
    }

    // 寻找指定UUID的Characteristic
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString: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: %@", [error localizedDescription]);

        return;
    }

    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
            NSLog(@"find the characteristic");

            [peripheral setNotifyValue:YES forCharacteristic:characteristic];

        }
    }
}

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

               NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        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;
    [self scan];

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

}

5.蓝牙后台运行


若要实现蓝牙4.0在APP进入后台时仍能工作,传输数据,不用写代码,只需要修改xxx-info.plist文件即可

在所需的背景模式中加入两项

使用CoreBluetooth应用程序共享数据  和  应用程序进行通信使用CoreBluetooth即可

CoreBluetooth——IOS蓝牙4.0使用心得的更多相关文章

  1. iOS蓝牙BLE4.0通信功能

    概述 iOS蓝牙BLE4.0通信功能,最近刚学的苹果,为了实现蓝牙门锁的项目,找了一天学习了下蓝牙的原理,亲手测试了一次蓝牙的通信功能,结果成功了,那么就把我学习的东西分享一下. 详细 代码下载:ht ...

  2. iOS蓝牙4.0开发

    文/starfox寒流(简书作者)原文链接:http://www.jianshu.com/p/974d165f78b5著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. iOS 蓝牙4.0 ...

  3. [iOS 基于CoreBluetooth的蓝牙4.0通讯]

    一.首先大致介绍下蓝牙4.0的模式,中心和周边: 一般情况下,iPhone作为中心,接收来自周边传感器(比如手环等)采集的数据. 二.那整一个数据通讯的协议是怎样的呢? 为什么要一层层搞这么复杂呢?据 ...

  4. iOS蓝牙4.0

    iOS的蓝牙用到了  CoreBluetooth 框架 首先导入框架 #import <CoreBluetooth/CoreBluetooth.h> 我们需要一个管理者来管理蓝牙设备,CB ...

  5. iOS 蓝牙4.0开发

    背景: 1.iOS的蓝牙不能用来传输文件.2.iOS与iOS设备之间进行数据通信,使用gameKit.framework3.iOS与其他非iOS设备进行数据通信,使用coreBluetooth.fra ...

  6. iOS蓝牙4.0协议简单介绍

    iOS开发蓝牙4.0的框架是CoreBluetooth,本文主要介绍CoreBluetooth的使用,关于本文中的代码片段大多来自github上的一个demo,地址是myz1104/Bluetooth ...

  7. https://github.com/coolnameismy/BabyBluetooth github上的一个ios 蓝牙4.0的库并带文档和教程

    The easiest way to use Bluetooth (BLE )in ios,even bady can use. 简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和 ...

  8. iOS蓝牙4.0开发(BLE)

    智能设备 和 app 通过 BLE通讯的两种模型 模型一:设备提供数据,app 展示数据: 比如小米手环 模型二:app提供数据,设备接收: 模型与corebluetooth的对应关系: 模型一:智能 ...

  9. iOS蓝牙4.0开发例子

    1建立中心角色 1 2 3 #import <CoreBluetooth/CoreBluetooth.h>  CBCentralManager *manager;  manager = [ ...

随机推荐

  1. char(10)和VARCHAR(10)主要的区别是什么?

    区别: 1.CHAR的长度是固定的,而VARCHAR2的长度是可以变化的, 如: 存储字符串“abc", 对于CHAR (10),表示你存储的字符将占10个字节(包括7个空字符), 而同样的 ...

  2. 【转发】揭秘Facebook 的系统架构

    揭底Facebook 的系统架构 www.MyException.Cn   发布于:2012-08-28 12:37:01   浏览:0次 0 揭秘Facebook 的系统架构 www.MyExcep ...

  3. ORACLE 查看有多个执行计划的SQL语句

    在SQL优化过程,有时候需要查看哪些SQL具有多个执行计划(Multiple Executions Plans for the same SQL statement),因为同一个SQL有多个执行计划一 ...

  4. 十五天精通WCF——第三天 client如何知道server提供的功能清单

     通常我们去大保健的时候,都会找姑娘问一下这里能提供什么服务,什么价格,这时候可能姑娘会跟你口述一些服务或者提供一份服务清单,这样的话大 家就可以做到童嫂无欺,这样一份活生生的例子,在wcf中同样是一 ...

  5. SQL Server 中的逻辑读与物理读

    首先要理解逻辑读和物理读: 预读:用估计信息,去硬盘读取数据到缓存.预读100次,也就是估计将要从硬盘中读取了100页数据到缓存. 物理读:查询计划生成好以后,如果缓存缺少所需要的数据,让缓存再次去读 ...

  6. 烂泥:centos单独编译安装gd库

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 这几天一直在弄一个商城系统,该系统的源码及数据库都已经上传并创建完毕.但是在安装该系统时,却提示缺少gd库.如下: 使用php探针查看,发现php确实没 ...

  7. FineReport层式报表解决大数据集展示问题攻略

    本文以填报报表为例,通过分页的方式,来解决大数据集展示的问题. 实现的思想就是通过在SQL里筛选部分数据库数据,以达到浏览器可以合理的展示报表页面.(数据分段,语句我这采用的是MYSQL,如果要用其他 ...

  8. 理解 OpenStack Swift (3):监控和一些影响性能的因素 [Monitoring and Performance]

    本系列文章着重学习和研究OpenStack Swift,包括环境搭建.原理.架构.监控和性能等. (1)OpenStack + 三节点Swift 集群+ HAProxy + UCARP 安装和配置 ( ...

  9. 荒芜的周六-PHP之面向对象(三)

    hi 又是开森的周六了.积攒的两周的衣服,终于是差不多洗完了.大下午的才来学点东西~~ 1.PHP面向对象(三) 四.OOP的高级实践 4.3 Static-静态成员 <?phpdate_def ...

  10. [转]二重积分换元法的一种简单证明 (ps:里面的符号有点小错误,理解就好。。。

    ---恢复内容开始--- 10.3二重积分的换元积分法 在一元函数定积分的计算中,我们常常进行换元,以达删繁就简的目的,当然,二重积分也有换元积分的问题. 首先让我们回顾一下前面曾讨论的一个事实. 设 ...