也是醉了,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. Bootstrap全局CSS样式之button和图片

    .btn-default--button的默认样式. .btn-primary--button的首选样式: .btn-success--button的成功样式: .btn-info--button的一 ...

  2. 九度OJ #1437 To Fill or Not to Fil

    题目描写叙述: With highways available, driving a car from Hangzhou to any other city is easy. But since th ...

  3. CSS 的导入方式 (link or import ?)

    前言 最常看见的CSS的使用方式有三种 1. 在span, div 等标签上直接使用 style 属性定义CSS <span style="color:blue">Th ...

  4. 对交换机VLAN及各种端口类型的理解

    每学习一种技术时,我们往往需要去了解why,即这个技术是为解决什么问题而出现的. VLAN全称为Virtual Local Area Network,即虚拟局域网,是逻辑上的一种划分.一般来说,如果交 ...

  5. for in 与for of

    最近在项目中需要用到遍历对象,用ES6 for of对象后报如下错误  TypeError: [object Object] is not iterable!,网上查询阮大神的教程发现“ES6 的有些 ...

  6. 多媒体开发之---h264快速运动估计算法

    #include "stdio.h"#include "stdlib.h"#include "malloc.h"#include " ...

  7. 赵雅智_SimpleCursorAdapter

    项目步骤 声明listView控件并获取显示的视图 获取显示的数据 设置显示的adapter 注冊点击事件 详细案例 实现效果: watermark/2/text/aHR0cDovL2Jsb2cuY3 ...

  8. SyntaxError:Strict mode does not allow function declaration in a lexically nested statement.

    问题描述   使用react-native init创建了一个新项目,在package.json中使用的react-native的版本如下: "dependencies": { & ...

  9. IE8 下背景图标不显示

    如图所示 : 微博微信前方各应有个图标,但是IE8下图标没有显示 css如下 .weibo_icon{background: url(../ieImages/weibo_icon.png)no-rep ...

  10. 字典树(Trie树) C++实现

    说明: 以下代码是个人按照自己的理解写的,可能有错误或者不太规范的地方,欢迎指出! 代码如下: //插入.删除.查询.遍历四种操作 //注意:四种操作的函数实现中,T都是指向上一个结点的指针,以此方便 ...