• 思路

    手机与设备间的通讯方式CoreBluetooth是比较常见且通用的。在iOS开发中需明晰以下几点

    1. 蓝牙4.0最多可联机7个设备,iPhone6以上都是蓝牙4.0
    2. 两台iPhone并不直接通过蓝牙互相搜索配对
    3. 苹果设备不支持和其他非苹果设备连接蓝牙,当然,除了蓝牙耳机和车载蓝牙之外
    4. 蓝牙传输的字节顺序是小端
    5. CoreBluetooth的最大传输单元是20个字节

    知识科普:

    字节顺序只是对内置数据类型而言

    例如对于一整型(int,int 是内置数据类型)数,比如 0x123456
    大端模式:
    高地址---------->低地址
    0x56 | 0x34 | 0x12
    小端模式:
    高地址 ---------->低地址
    0x12 | 0x34 | 0x56
  • 流程

    以中心设备为例分析整个流程

    1.实例化中心设备管理者

    cManager = CBCentralManager(delegate: self, queue: nil)

    2.监测状态为PowOn,并搜索附近设备

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
    scanForServices()
    } else {
    print("\(central.state)")
    }
    }

    3.发现外设,保存并展示

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    if let name = peripheral.name {
    if !list.contains(name) {
    list.append(name)
    dict[name] = peripheral
    table.reloadData()
    }
    }
    }

    4.根据需要选择连接的外设

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 连接设备
    if let pheral = dict[list[indexPath.row]] {
    cManager?.connect(pheral, options: nil)
    }
    }

    5.连接外设,失败/成功,成功则扫描外设服务

    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
    print("连接外设失败")
    } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    // 停止扫描
    central.stopScan()
    print("连接外设成功") peripheral.delegate = self
    self.peripheral = peripheral // 扫描外设的服务
    peripheral.discoverServices([CBUUID(string: "打印")])
    }

    6.回调中发现服务

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    var findService: CBService?
    for item in peripheral.services ?? [] {
    print(item.uuid)
    // 如果服务调用在service中
    if item.uuid.isEqual(CBUUID(string: "打印")) {
    findService = item
    }
    }
    if let findService = findService {
    peripheral.discoverCharacteristics(nil, for: findService)
    }
    }

    7.查询服务下面的特征,回调中返回 then发送打印数据

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    for item in service.characteristics ?? [] {
    if item.uuid.isEqual(CBUUID(string: "打印")) {
    // 读取成功回调didUpdateValueForCharacteristic
    self.characteristic = item // 接收一次(是读一次信息还是数据经常变实时接收视情况而定, 再决定使用哪个)
    peripheral.readValue(for: item) // 订阅、实时接收
    peripheral.setNotifyValue(true, for: item) // 发送下行指令【发送一条】
    guard let data = "硬件工程师给我的指令, 发送给蓝牙该指令, 蓝牙会给我返回一条数据".data(using: .utf8) else { return }
    self.peripheral?.writeValue(data, for: item, type: .withResponse)
    } // 当发现characteristic有descriptor,回调didDiscoverDescriptorsForCharacteristic
    peripheral.discoverDescriptors(for: item)
    }
    }

    8.从外围设备读取数据

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    //characteristic.value就是蓝牙传递过来的值
    print("\(String(describing: characteristic.value))")
    }

    9.中心设备读取外设实时数据

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.isNotifying {
    peripheral.readValue(for: characteristic)
    } else {
    print("notification stoped on \(characteristic)")
    self.cManager?.cancelPeripheralConnection(peripheral)
    }
    }
  • 结束

iOS之CoreBluetooth的更多相关文章

  1. [iOS 基于CoreBluetooth的蓝牙4.0通讯]

    一.首先大致介绍下蓝牙4.0的模式,中心和周边: 一般情况下,iPhone作为中心,接收来自周边传感器(比如手环等)采集的数据. 二.那整一个数据通讯的协议是怎样的呢? 为什么要一层层搞这么复杂呢?据 ...

  2. iOS蓝牙--CoreBluetooth基本使用

    蓝牙使用步骤: 1. 扫描外设 2. 连接外设 3. 连上外设后,获取指定外设的服务 4. 获取服务后,遍历服务的特征,得到可读,可写等特征,然后与中心管理者进行数据交互 附上代码 一:导入框架 #i ...

  3. iOS CoreBluetooth 教程

    去App Store搜索并下载“LightBlue”这个App,对调试你的app和理解Core Bluetooth会很有帮助. ================================ Cor ...

  4. CBCentralManagerDelegate Protocol 委托协议相关分析

    总体概述 CBCentralManagerDelegate 协议中定义了一系列方法列表,这些方法是委托对象必须要实现的方法(也有可选择的),当中央管理器的相应变化就会调用委托对象中实现的相应方法. M ...

  5. iOS蓝牙开发CoreBluetooth快速入门

    在iOS开发中,实现蓝牙通信有两种方式,一种是使用传统的GameKit.framework,另一种就是使用在iOS 5中加入的CoreBluetooth.framework. 利用CoreBlueto ...

  6. ios CoreBluetooth 警告 is being dealloc'ed while pending connection

    ios CoreBluetooth 警告 is being dealloc'ed while pending connection CoreBluetooth[WARNING] <CBPerip ...

  7. iOS之蓝牙开发—CoreBluetooth详解

    CoreBluetooth的API是基于BLE4.0的标准的.这个框架涵盖了BLE标准的所有细节.仅仅只有新的iOS设备和Mac是和BLE标准兼容.在CoreBluetooth框架中,有两个主要的角色 ...

  8. iOS 蓝牙(GameKit CoreBluetooth)

    利用GameKit框架实现ios设备的蓝牙通讯,导入框架:#import <GameKit/GameKit.h>  , 注意: 此框架只能用于ios设置间蓝牙通讯 如今苹果开放了接口来实现 ...

  9. iOS 蓝牙开发之(CoreBlueTooth)

    CoreBlueTooth 简介: 可用于第三方的蓝牙交互设备 设备必须支持蓝牙4.0 iPhone的设备必须是4S或者更新 iPad设备必须是iPad mini或者更新 iOS的系统必须是iOS 6 ...

随机推荐

  1. AtCoder Beginner Contest 173

    比赛链接:https://atcoder.jp/contests/abc173/tasks A - Payment 题意 计算只用 $1000$ 元支付某个价格 $n$ 的找零是多少. 代码 #inc ...

  2. Codeforces Global Round 7 D2. Prefix-Suffix Palindrome (Hard version)(Manacher算法)

    题意: 取一字符串不相交的前缀和后缀(可为空)构成最长回文串. 思路: 先从两边取对称的前后缀,之后再取余下字符串较长的回文前缀或后缀. #include <bits/stdc++.h> ...

  3. hdu5662 YJQQQAQ and the function (单调栈)

    Problem Description YJQQQAQ has an array A of length n. He defines a function fl,r,k where l,r,k are ...

  4. Codeforces Round #652 (Div. 2) B. AccurateLee(思维)

    题意: 给你一个01字符串,现在你可以删除其中的一些子序列,要求如下:当遇到1 0的俩个连续子字符串后,可以删除其中的一个字符,现在要求把他删到尽量最短并且字典序最小,输出最后的字符串 题解: 刚开始 ...

  5. bnuoj24252 Divide

    Alice and Bob has found a island of treasure in byteland! They find N kinds of treasures on the isla ...

  6. 洛谷 P2880 [USACO07JAN]Balanced Lineup G (ST表模板)

    题意:给你一组数,询问\(q\)次,问所给区间内的最大值和最小值的差. 题解:经典RMQ问题,用st表维护两个数组分别记录最大值和最小值然后直接查询输出就好了 代码: int n,q; int a[N ...

  7. 洛谷 P1077 摆花 (背包DP)

    题意:有\(n\)种花,每种花有\(a_i\)盆,现在要摆\(m\)盆花,花的种类从\([1,n]\)有序排放,问有多少种方案数. 题解:这题可以借用01背包的思路,感觉更好想一点,我们首先枚举\(n ...

  8. AtCoder Beginner Contest 173 C - H and V (二进制枚举)

    题意:有一张图,.表示白色,#表示黑色,每次可以将多行和多列涂成红色(也可不涂),问有多少种方案,使得剩下黑点的个数为\(k\). 题解:又学到了新的算法qwq,因为这题的数据范围很小,所以可以用二进 ...

  9. 牛客编程巅峰赛S1第5场 - 青铜&白银 A.凯撒密码(字符串)

    题意:给你一个加密的字符串,以及偏移量,求对应的明文. 题解:根据样例,不难看出模板串是:\(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq ...

  10. WSL2 Ubuntu apt-get update失败

    情况: 这个问题在github上也有讨论:https://github.com/microsoft/WSL/issues/4342 不过经过我的尝试,是DNS问题,这是默认的配置: 这个配置来自win ...