也是醉了,CB这个API到现在也没有Swift的文档。最新的文档还是3年前还是4年前的OC版的,被雷的外焦里嫩的。自己一点一点写成Swift还各种报错,最坑的是这些错误压根找不到解决方案。索性自己做个个人专用的蓝牙通信库,顺便梳理下这一块。这篇博文讲中心模式

 
//----------------------------------------------------------------------------------
//      
     
     
     
     
     
     
    基本
//----------------------------------------------------------------------------------

首先设置代理类

class CentralManagerPro:
NSObject,
CBCentralManagerDelegate

创建中心设备管理器

centralManager = CBCentralManager(delegate:
self, queue: nil,
options: nil)

delegate就是处理中心设备管理器相关事件的,继承CBCentralManagerDelegate的一系列方法全部写在里面。这里就是self,也就是这个管理器所在的类

特别注意,这个中心设备管理器不要重复生成。不然会报错,而且上网搜也没有解决方法。我就为此花了老半天。

开始扫描

if
centralManager.state
== .poweredOn {

centralManager.scanForPeripherals(withServices:
nil, options:
nil)

return true

}else {

return false

}

虽然网上没有任何资料这么写,但是目前新版本里如果不判断中心设备是否开启就直接进行活动会报错。下面所有函数相同

这里的withServices是周边设备内部需要有的服务,如果不指定那所有搜索到的周边设备都会反馈

扫描到以后为了省电,停止扫描

centralManager.stopScan()

连接扫描到的设备

if peripheral !=
nil {

centralManager.connect(peripheral,
options: nil)

return true

}else {

return false

}

连接成功呼出func centralManager(_ central: CBCentralManager,
didConnect
peripheral: CBPeripheral)

连接失败呼出func centralManager(_ central: CBCentralManager,
didFailToConnect
peripheral: CBPeripheral,
error: Error?)

搜索服务和特征 

搜索连接上的周边设备有的服务

if peripheral !=
nil {

peripheral.discoverServices(serviceUUIDs)

}

这样的好处是防止搜索以及实效的周边设备,避免程序崩溃

搜索到以后会自动呼出func peripheral(_ peripheral: CBPeripheral,
didDiscoverServices error: Error?)

搜索到自己要的服务以后,进一步搜索自己要的特性

peripheral.discoverCharacteristics(characteristicUUIDs,
for: service)

搜索完成后会呼出 func peripheral(_ peripheral: CBPeripheral,
didDiscoverCharacteristicsFor
service: CBService,
error: Error

搜索到特性后,获取特性的值

peripheral.readValue(for:
char)

获得了值后会自动呼出如下函数 func peripheral(_ peripheral: CBPeripheral,
didUpdateValueFor
characteristic: CBCharacteristic, error: Error?)

改写特性的值

peripheral.writeValue(data, for: char, type:
CBCharacteristicWriteType.withoutResponse)

CBCharacteristicWriteType.withoutResponse这样设置后自己会运行

服务的特性的值被改写后会自动呼出如下函数

(CBCharacteristicWriteType.withoutResponse这样设置后)

//didWriteValueFor

func peripheral(_
peripheral: CBPeripheral,
didWriteValueFor characteristic:
CBCharacteristic, error:
Error?) {

if let
error = error {

print("Write失敗...error:
\(error)")

return

}

print("Write成功!")

}

获取特性值的更新通知

peripheral.setNotifyValue(true, for:
char)

不获取特性值的更新通知

peripheral.setNotifyValue(false,
for: char)

状态更新后会自动呼出如下函数func peripheral(_ peripheral: CBPeripheral,
didUpdateNotificationStateFor
characteristic: CBCharacteristic,
error: Error?)

//----------------------------------------------------------------------------------
//      
     
     
     
     
     
  回调函数(继承协议)
//----------------------------------------------------------------------------------

//-------------------------------------------------------------------

//      
     
    
     
   
CBCentralManagerDelegate

//-------------------------------------------------------------------

发现了周边设备的话,回自动呼出下面这个函数

///didDiscover

func centralManager(_ central: CBCentralManager,
didDiscover
peripheral: CBPeripheral,
advertisementData:
[String : Any],
rssi RSSI: NSNumber)
{

let state
= "discoverd
peripheral: \(peripheral.services)\n"

print(state)

self.peripheral =
peripheral

}

连接结果

//didConnect

func centralManager(_
central: CBCentralManager,
didConnect peripheral: CBPeripheral)
{

let state =
"central: connected!\n"

print(state)

}

//didFailToConnect

func centralManager(_
central: CBCentralManager,
didFailToConnect peripheral:
CBPeripheral, error:
Error?) {

let state =
"central: failed to connected\n"

print(state)

}

//-------------------------------------------------------------------

//      
     
    
     
 
  CBPeripheralDelegate

//-------------------------------------------------------------------

搜索服务完毕后会自动呼出如下函数

//didDiscoverServices

func peripheral(_
peripheral: CBPeripheral,
didDiscoverServices error: Error?)
{

guard let
services = peripheral.services
else{

print("error")

return

}

print("\(services.count)個のサービスを発見。\(services)")

}

搜索完指定服务的特性后会呼出如下函数

//didDiscoverCharacteristicsFor

func peripheral(_
peripheral: CBPeripheral,
didDiscoverCharacteristicsFor service:
CBService, error:
Error?) {

if let
error = error {

print("error:
\(error)")

return

}

let characteristics =
service.characteristics

print("Found
\(characteristics?.count
?? 0) characteristics! :
\(characteristics)")

}

获取指定的特性的值时会呼出如下函数

//didUpdateValueFor

func peripheral(_
peripheral: CBPeripheral,
didUpdateValueFor characteristic:
CBCharacteristic, error:
Error?) {

if let
error = error {

print("Failed... error:
\(error)")

return

}

print("Succeeded! service
uuid:
\(characteristic.service.uuid),
characteristic uuid:
\(characteristic.uuid),
value:
\(characteristic.value)")

}

服务的特性的值被改写后会自动呼出如下函数

(CBCharacteristicWriteType.withoutResponse这样设置后)

//didWriteValueFor

func peripheral(_ peripheral: CBPeripheral,
didWriteValueFor
characteristic: CBCharacteristic,
error: Error?)
{

if let error
= error {

print("Write失敗...error: \(error)")

return

}

print("Write成功!")

}

状态更新后会自动呼出如下函数

//didUpdateNotificationStateFor

func peripheral(_
peripheral: CBPeripheral,
didUpdateNotificationStateFor characteristic:
CBCharacteristic, error:
Error?) {

if let
error = error {

print("Notify状態更新失敗...error:
\(error)")

} else {

print("Notify状態更新成功!
isNotifying:
\(characteristic.isNotifying)")

}

}

CoreBluetooth Central模式 Swift版的更多相关文章

  1. Swift版iOS游戏框架Sprite Kit基础教程下册

    Swift版iOS游戏框架Sprite Kit基础教程下册 试读下载地址:http://pan.baidu.com/s/1qWBdV0C 介绍:本教程是国内唯一的Swift版的Spritekit教程. ...

  2. Swift版音乐播放器(简化版),swift音乐播放器

    这几天闲着也是闲着,学习一下Swift的,于是到开源社区Download了个OC版的音乐播放器,练练手,在这里发扬开源精神, 希望对大家有帮助! 这个DEMO里,使用到了 AudioPlayer(对音 ...

  3. 快速排序OC、Swift版源码

    前言: 你要问我学学算法在工作当中有什么用,说实话,当达不到那个地步的时候,可能我们不能直接的感觉到它的用处!你就抱着这样一个心态,当一些APP中涉及到算法的时候我不想给其他人画界面!公司的项目也是暂 ...

  4. iOS可视化动态绘制八种排序过程(Swift版)

    前面几篇博客都是关于排序的,在之前陆陆续续发布的博客中,我们先后介绍了冒泡排序.选择排序.插入排序.希尔排序.堆排序.归并排序以及快速排序.俗话说的好,做事儿要善始善终,本篇博客就算是对之前那几篇博客 ...

  5. swift版的CircleView

    swift版的CircleView 效果图 源码 // // CircleView.swift // CircleView // // Created by YouXianMing on 15/10/ ...

  6. swift版的GCD封装

    swift版的GCD封装 说明 本人针对swift封装了GCD,包括GCDQueue,GCDGroup,GCDTimer以及GCDSemaphore,使用较为便利. 源码 https://github ...

  7. swift版的StringAttribute

    swift版的StringAttribute 效果 源码 https://github.com/YouXianMing/Swift-StringAttribute // // StringAttrib ...

  8. swift版的元组

    swift版的元组 说明 元组的内容并不多,使用的话跟普通变量类似,以下是测试源码: // // ViewController.swift // Tuples // // Created by You ...

  9. swift版的枚举变量

    swift版的枚举变量 swift的枚举类型跟普通的类是极为类似的,使用的时候,请不要以为他是一个常量,以下是测试用源码 // // ViewController.swift // SwiftEnum ...

随机推荐

  1. BUPT复试专题—打牌(2011)

    https://www.nowcoder.com/practice/82442ee76977479e8ab4b88dfadfca9f?tpId=67&tqId=29640&tPage= ...

  2. 转: 环信联合创始人:App主流反垃圾服务难点和技术实现全解析

    转:http://science.china.com.cn/2016-03/24/content_8659834.htm 发布时间: 2016-03-24 13:15:02  |  来源: 全球财经网 ...

  3. stl_内存基本处理工具

    内存基本处理工具 STL定义5个全局函数.作用于初始化空间上.各自是:用于构造的construct(),用于析构的destroy(),uninitialized_copy(),uninitialize ...

  4. angular1.x 组件开发

    搜索框组件开发: 1.注册组件 app.js angular.module("myApp",[]) .component("nameSearch",{ temp ...

  5. 面向接口的webservice发布方式

    import javax.jws.WebService; /**面向接口的webservice发布方式 */ @WebService public interface JobService { pub ...

  6. saltstack安装配置(syndic)

    syndic是saltstack用来做集群部署的,一般结构如图: syndic是一个特殊的minion,syndic类继承于minion类,syndic可以看作一个代理,只做数据传递. CentOS上 ...

  7. Activity左边滑出,右边滑入的动画切换

    Activity左边滑出,右边滑入的动画切换 转载请注明出处:http://blog.csdn.net/u012301841/article/details/46920809 大家都知道Android ...

  8. Arcgis Engine(ae)接口详解(2):featureClass查询

    //属性查询~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //IQueryFilter代表查询条件,QueryFilterClass代表只限于属性查询(就是没有空间查询) ...

  9. Django 之ORM操作

    1.什么是ORM? 全称关系对象映射Object Relational Mapping(简称ORM),是通过描述面向对象与数据库之间的对应的元数据,将对象持久化的更新到数据库中. 有了ORM,就不需要 ...

  10. python day-3 基本数据类型

    1. 编码 1. 最早的计算机编码是ASCII. 美国人创建的. 包含了英文字母(大写字母, 小写字母). 数字, 标点等特殊字符!@#$% 128个码位 2**7 在此基础上加了一位 2**8 8位 ...