(转)iOS蓝牙调用的一般流程

文章转自:http://www.cnblogs.com/ctaodream/archive/2013/07/03/3169962.html

一、服务端(也叫周边设备吧。。脑残的翻译)

1.实现类必须遵守协议 CBPeripheralManagerDelegate

2.需要的主要类有:

@property(strong,nonatomic) CBPeripheralManager *peripheraManager;

@property(strong,nonatomic) CBMutableCharacteristic *customerCharacteristic;

@property (strong,nonatomic) CBMutableService *customerService;

3.调用流程代码中有注释

//
//  ViewController.m
//  BlueToothDemo
//
//  Created by PSH_Chen_Tao on 7/3/13.
//  Copyright (c) 2013 wolfman. All rights reserved.
//

#import "ViewController.h"
static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90";

static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B";
@interface ViewController ()

@end

@implementation ViewController

@synthesize peripheraManager;
@synthesize customerCharacteristic;
@synthesize customerService;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //初始化后会直接调用代理的  - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral

    peripheraManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
  //  [peripheraManager startAdvertising:nil];

}

-(void)setUp{
    CBUUID *characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID];
    customerCharacteristic = [[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
    CBUUID *serviceUUID = [CBUUID UUIDWithString:kServiceUUID];
    customerService = [[CBMutableService alloc]initWithType:serviceUUID primary:YES];
    [customerService setCharacteristics:@[characteristicUUID]];
    //添加后就会调用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
    [peripheraManager addService:customerService];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma  mark -- CBPeripheralManagerDelegate
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    switch (peripheral.state) {
            //在这里判断蓝牙设别的状态  当开启了则可调用  setUp方法(自定义)
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"powered on");
            [self setUp];
            break;
            case CBPeripheralManagerStatePoweredOff:
            NSLog(@"powered off");
            break;

        default:
            break;
    }
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
    if (error == nil) {
        //添加服务后可以在此向外界发出通告 调用完这个方法后会调用代理的
        //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
        [peripheraManager startAdvertising:@{CBAdvertisementDataLocalNameKey : @"Service",CBAdvertisementDataServiceUUIDsKey : [CBUUID UUIDWithString:kServiceUUID]}];
    }

}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    NSLog(@"in peripheralManagerDidStartAdvertisiong:error");
}
@end

二、客户端(也叫中心设备吧)

1.实现类要遵守协议<CBCentralManagerDelegate,CBPeripheralDelegate>

2.主要用到的类有

@property(strong,nonatomic)CBCentralManager *centralManager;

@property(strong,nonatomic)NSMutableData *mutableData;

@property(strong,nonatomic)CBPeripheral *peripheral;

3.一般的流程

//
//  ViewController.m
//  BlueToothClient
//
//  Created by PSH_Chen_Tao on 7/3/13.
//  Copyright (c) 2013 wolfman. All rights reserved.
//

#import "ViewController.h"
static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90";

static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B";
@interface ViewController ()

@end

@implementation ViewController

@synthesize centralManager;
@synthesize mutableData;
@synthesize peripheral;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //初始化后会调用代理CBCentralManagerDelegate 的 - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma  mark -- CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
            //判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备  你可以
            //指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备
            //scanForPeripheralsWithServices方法调用完后会调用代理CBCentralManagerDelegate的
            //- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
        case CBCentralManagerStatePoweredOn:
            [centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : YES}];

            break;

        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral) {
        self.peripheral = peripheral;
        //发现设备后即可连接该设备 调用完该方法后会调用代理CBCentralManagerDelegate的- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral表示连接上了设别
        //如果不能连接会调用 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
        [centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : YES}];
    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"has connected");
    [mutableData setLength:0];
    self.peripheral.delegate = self;
    //此时设备已经连接上了  你要做的就是找到该设备上的指定服务 调用完该方法后会调用代理CBPeripheralDelegate(现在开始调用另一个代理的方法了)的
    //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    [self.peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];

}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //此时连接发生错误
    NSLog(@"connected periphheral failed");
}

#pragma mark -- CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if (error==nil) {
        //在这个方法中我们要查找到我们需要的服务  然后调用discoverCharacteristics方法查找我们需要的特性
        //该discoverCharacteristics方法调用完后会调用代理CBPeripheralDelegate的
        //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        for (CBService *service in peripheral.services) {
            if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
                [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error==nil) {
        //在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
        //当setNotifyValue方法调用后调用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {

                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error==nil) {
        //调用下面的方法后 会调用到代理的- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        [peripheral readValueForCharacteristic:characteristic];
    }
}

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

}

@end

(转)iOS蓝牙调用的一般流程,布布扣,bubuko.com

时间: 2024-12-28 17:34:08

(转)iOS蓝牙调用的一般流程的相关文章

iOS蓝牙开发框架

iOS支持了蓝牙4.0后,很多智能硬件开始通过蓝牙与手机进行通讯互交,比如蓝牙秤,各种蓝牙医疗设备等.每个设备有不同的型号,且不断迭代更新,软件如何支持多种设备,如何区分多个设备,并分别对不同的设备进行控制,我给大家分享一个我总结的蓝牙开发框架. 核心蓝牙控制采用iOS自带的CoreBluetooth,本身该库已经可以很好的操控蓝牙设备,我的框架也仅仅是对该库的进一步封装,目的是解决如下几个问题1 区分多个设备的连接状态2 多个设备各自的蓝牙通信处理 我的蓝牙框架将设备连接,设备使能通道开启,设

iOS app集成支付宝支付流程及后台php订单签名处理

iOS app集成支付宝支付流程 1: 开通支付宝商户 由公司去支付宝 https://b.alipay.com/order/serviceIndex.htm 签约支付宝开通支付宝商家: 2:商户支付宝开通无线支付功能 开通商户支付宝之后,虽然可以获取到应用使用的 key和id,如果如果不开通无线支付功能的话,会在app集成的时间 提示商户未开通无线支付功能的错误: 开通商户支付宝-无线支付功能,请在商户支付宝后台,按要求提供审核材料开通: 3:在商户支付宝后台下载SDK 在商户支付宝后台,即可

iOS蓝牙编程指南 -- 核心蓝牙概述

小引 随着穿戴设备和智能家居的热情不断,app蓝牙的开发也很火热,基于iOS蓝牙的开发资料有不少,但是最最值得学习的必然是apple自家的文档啦,我之前的项目基于蓝牙4.0,开发过程中用到Core Bluetooth框架,算是我学习的笔记吧!涉及到几个部分,我打算分开把他们整理出来,本篇文章通过对Core Bluetooth Programming Guide的翻译,为大家介绍iOS蓝牙4.0编程的一些术语和概念,后续文章将会简单介绍下代码的流程.本人实力有限,了解的深度不是很广,还请各位看官轻

IOS 蓝牙相关-BabyBluetooth蓝牙库介绍(4)

BabyBluetooth 是一个最简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和mac osx. 特色: 基于原生CoreBluetooth框架封装的轻量级的开源库,可以帮你更简单地使用CoreBluetooth API. CoreBluetooth所有方法都是通过委托完成,代码冗余且顺序凌乱.BabyBluetooth使用block方法,可以重新按照功能和顺序组织代码,并提供许多方法减少蓝牙开发过程中的代码量. 链式方法体,代码更简洁.优雅. 通过channel切换区

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

The easiest way to use Bluetooth (BLE )in ios,even bady can use. 简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和mac osx. 为什么使用它? 1:基于原生CoreBluetooth框架封装的轻量级的开源库,可以帮你更简单地使用CoreBluetooth API. 2:CoreBluetooth所有方法都是通过委托完成,代码冗余且顺序凌乱.BabyBluetooth使用block方法,可以重新按照功能和顺序

iOS蓝牙开发(一)蓝牙相关基础知识

原文链接: http://liuyanwei.jumppo.com/2015/07/17/ios-BLE-1.html iOS蓝牙开发(一)蓝牙相关基础知识: 蓝牙常见名称和缩写 MFI ======= make for ipad ,iphone, itouch 专们为苹果设备制作的设备 BLE ==== buletouch low energy,蓝牙4.0设备因为低耗电,所以也叫做BLE peripheral,central == 外设和中心,发起连接的时central,被连接的设备为peri

ios闪光灯调用

引入 #import <AVFoundation/AVFoundation.h> 打开闪光灯 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if (![device hasTorch]) {//判断是否有闪光灯 NSLog(@"no torch"); }else{ [device lockForConfiguration:nil];//锁定闪光

iOS 企业证书发布app 流程

企业发布app的 过程比app store 发布的简单多了,没那么多的要求,哈 但是整个工程的要求还是一样,比如各种像素的icon啊 命名规范啊等等. 下面是具体的流程 1.修改你的 bundle identifier 为你的企业的app id : 2.修改Edit scheme 3.修改为 Release 4.修改bulid setting 的code sign:为企业的 mobileprifile 5.然后 Product  archive 归档构建你的app 6.选择 distrbutio

支持APP手机应用(android和ios)接口调用 ,传输验证可用 shiro 的 MD5、SHA 等加密

请认准本正版代码,售后技术有保障,代码有持续更新.(盗版可耻,违者必究)         此为本公司团队开发 ------------------------------------------------------------------------------------------------------------------------- 1. 有 oracle .msyql.spring3.0.spring4.0  一共 4 套版本全部提供没有打jar没有加密的源代码(最下面截图2