也是醉了,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. vim 精确匹配查找单词【转】

    删除文件中所有的空行:g/^\s*$/d 去掉所有的行尾空格::%s/\s\+$// 整个文件特定字符串的替换:%s/old_word/new_word/g 删除从当前行开始到最后一行的所有内容:., ...

  2. [Unit Testing] Test async function with Jasmine

    Most of time, when we want to test function call inside a promise, we can do: it('Should be async', ...

  3. MRP Force Reservation的作用

    生产单根据BOM计算出相应的物料需求,生产领料单stock.picking ( internal moves) Stock.picking使用工作流自动计算库存量,如果库存量够,则使用 test_as ...

  4. 使用脚本删除ios工程中未使用图片

    使用脚本删除ios工程中未使用图片 最近在读唐巧大神的<iOS开发进阶>,学到了一个大招:使用脚本删除ios中未使用的图片(纸书上有点小问题,参考github上的issue:使用脚本删除i ...

  5. Spring官方文档翻译——15.1 介绍Spring Web MVC框架

    Part V. The Web 文档的这一部分介绍了Spring框架对展现层的支持(尤其是基于web的展现层) Spring拥有自己的web框架--Spring Web MVC.在前两章中会有介绍. ...

  6. org.hibernate.id.IdentifierGenerationException错误解决方法

    org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before ...

  7. 小程序 单页应用的 tab切换 实现

    小程序 单页应用的  tab切换 实现

  8. 按行读入xml文件,删除不需要的行 -Java

    删除挺麻烦的,这里其实只是把需要的行存到arraylist中再存到另一个文件中 import java.io.BufferedReader;import java.io.BufferedWriter; ...

  9. Shell编程——Shell中的数学运算

    在Linux Shell中进行数学运算,通常能够使用的运算符有: 简单运算: let [] (()) 高级运算: expr bc 1.let命令 let命令是bash内置命令.能够实现简单的算术以及逻 ...

  10. Latex 5: LaTeX资料下载

    转: LaTeX资料下载 最全latex资料下载   LaTeX命令速查手册1