Swift学习第十三枪-使用Swift开发IOS中蓝牙4.0的开发流程

2024-05-04 15:32

本文主要是介绍Swift学习第十三枪-使用Swift开发IOS中蓝牙4.0的开发流程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前面总结了几篇关于Swift的使用,今天要讲的是关于使用Swift开发IOS中蓝牙4.0的开发流程,我以前只是会搞android的蓝牙开发,最近开始了Swift的学习,作为一个swift爱好者,想把蓝牙4.0的这个装逼神器在swift中使用一下。
使用Swift开发IOS中蓝牙4.0的开发流程有如下的几个步骤:

  • 建立桥接文件

  • 案例的实现

1. 建立桥接文件

1.1在用Swift使用OC中得类文件的时候,需要进行桥接,首先建一个.h的头文件。
注意:桥接文件的命名规则:项目名-Bridging-Header.Swift

//
//  Swfit-BLE-Bridging-Header.h
//  Swift-BLE
//
//  Created by lidong on 16/7/3.
//  Copyright © 2016年 李东. All rights reserved.
//
#import <CoreBluetooth/CoreBluetooth.h>

1.2 在Build-settings -> Swift Complier - Code Generaton —>Objective C Briding Herder中添加自己的桥接文件。
如下图:
这里写图片描述

2.案例的实现

首先,CoreBluetooth库文件为我们提供两个类CBCentralManagerDelegate,CBPeripheralDelegate ,是蓝牙操作的核心类。

CBCentralManagerDelegate 中心管理器的代理类

CBPeripheralDelegate 外围设备的代理类

2.1创建CBCentralManager,设置代理
var  myCentralManager:CBCentralManager!
myCentralManager = CBCentralManager()
myCentralManager.delegate = self
2.2启动扫描发现设备

print("扫描设备。。。。 ")         myCentralManager.scanForPeripheralsWithServices(nil, options: nil)
//蓝牙的状态func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {switch (central.state) {case CBCentralManagerState.PoweredOn:print("蓝牙已打开, 请扫描外设!");break;case CBCentralManagerState.PoweredOff:print("蓝牙关闭,请先打开蓝牙");default:break;}}//发现设备func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {print("--didDiscoverPeripheral-")if peripheral.name == DEVICENAME{self.myPeripheral = peripheral;self.myCentralManager = central;central.connectPeripheral(self.myPeripheral, options: nil)print(self.myPeripheral);}}
2.3 发现设备后,连接设备,连接成功,关闭中心啊管理者的扫描,发现设备的服务,设置外围设备的代理
 //设备已经接成功func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {print("---------didConnectPeripheral-")print(central)print(peripheral)//关闭扫描self.myCentralManager.stopScan()self.myPeripheral.delegate = selfself.myPeripheral.discoverServices(nil)print("扫描服务...");}
2.4 根据服务发现特征
 /**发现服务调用次方法- parameter peripheral: <#peripheral description#>- parameter error:      <#error description#>*/func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {print("---发现服务调用次方法-")for s in peripheral.services!{peripheral.discoverCharacteristics(nil, forService: s)print(s.UUID.UUIDString)}}/**根据服务找特征- parameter peripheral: <#peripheral description#>- parameter service:    <#service description#>- parameter error:      <#error description#>*/func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {print("----发现特征------")for c in service.characteristics! {if c.UUID.UUIDString == "2AF0"{print(c.UUID.UUIDString)peripheral.setNotifyValue(true, forCharacteristic: c)}if c.UUID.UUIDString == "2AF1"{print(c.UUID.UUIDString)self.writeCharacteristic = c}}}
2.5向设备发送指令,获取数据
 /**写入后的回掉方法- parameter peripheral:     <#peripheral description#>- parameter characteristic: <#characteristic description#>- parameter error:          <#error description#>*/func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {print("didWriteValueForCharacteristic")}/**<#设置特征为正在监听,读取数据#>- parameter peripheral:     <#peripheral description#>- parameter characteristic: <#characteristic description#>- parameter error:          <#error description#>*/func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {print("-----didUpdateNotificationStateForCharacteristic-----")if (error != nil) {print(error?.code);}//Notification has startedif(characteristic.isNotifying){peripheral.readValueForCharacteristic(characteristic);print(characteristic.UUID.UUIDString);}}/**获取外设的数据- parameter peripheral:     <#peripheral description#>- parameter characteristic: <#characteristic description#>- parameter error:          <#error description#>*/func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {print("----didUpdateValueForCharacteristic---")if  characteristic.UUID.UUIDString == "2AF0"  {let data:NSData = characteristic.value!print(data)let  d  = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))print(d)let s:String =  HexUtil.encodeToString(d)if s != "00" {result += sprint(result )print(result.characters.count )}if result.characters.count == 38 {lable.text = result}}}
2.6 发送指令的方法
    /**发送指令到设备*/func writeToPeripheral(bytes:[UInt8]) {if writeCharacteristic != nil {let data1:NSData = dataWithHexstring(bytes)self.myPeripheral.writeValue(data1, forCharacteristic: writeCharacteristic, type: CBCharacteristicWriteType.WithResponse)} else{}}/**将[UInt8]数组转换为NSData- parameter bytes: <#bytes description#>- returns: <#return value description#>*/func dataWithHexstring(bytes:[UInt8]) -> NSData {let data = NSData(bytes: bytes, length: bytes.count)return data}

总结:使用Swift开发IOS中蓝牙4.0的开发流程基本就是如上两大步骤,六小步骤,如果有不明白,可以联系我。

注意:蓝牙调试代码只能真机,模拟器是没效果的。

代码地址https://github.com/lidong1665/Swift-BLE

截图

这篇关于Swift学习第十三枪-使用Swift开发IOS中蓝牙4.0的开发流程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/959520

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Nginx分布式部署流程分析

《Nginx分布式部署流程分析》文章介绍Nginx在分布式部署中的反向代理和负载均衡作用,用于分发请求、减轻服务器压力及解决session共享问题,涵盖配置方法、策略及Java项目应用,并提及分布式事... 目录分布式部署NginxJava中的代理代理分为正向代理和反向代理正向代理反向代理Nginx应用场景

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash