iOS 解决蓝牙配对弹框的问题,解决ANCS带来的问题,获取已配对(已绑定)设备列表,

不知道小伙伴们在开发蓝牙相关app时,有没有遇到出现配对弹框的情况,如下:


WechatIMG2428.jpeg

在我的另一文章里面也能看到配对弹框的出来;flutter 实战App 之 提词器app;也是为了解决这个app的问题,就好好研究一下此问题~

上面的弹框,如果客户点击了取消,那么一切正常;如果客户点击了配对,那么你就会发现,你下次无法扫描到此设备,也没有办法去连接它,或者断开它。即使你关闭手机蓝牙开关,再打开,也没有用, 就算你把app kill掉,也无法解决。草~~

回到正题:什么时候会弹出配对,什么原因导致的

当硬件设备支持了ANCS标准,就会弹出配对框,( 苹果iOS 7开始提供的ANCS协议,ANCS(苹果通知中心, Apple Notification Center Service)的目的是提供给蓝牙外设一种简单、方便的获取iOS设备通知信息的方式。使得蓝牙手环、手表可以收到苹果手机的来电、短信及各种应用的通知信息),更多信息可以参阅下面的链接,相信对你帮助

iOS ANCS介绍
处理ANCS设备连接绑定问题

那什么原因导致,选择了配对后,下次就再也没有办法发现外设呢;蓝牙有2层连接,一层连接是外设与app应用层之间的连接,还有一层连接是系统层的连接,也就是外设支持ANCS服务,客户选择了配对后,就建立起了连接。 选择配对后,如上所述,即使你关闭手机蓝牙开关,再打开,也没有用, 就算你把app kill掉,也无法解决,但此时,如果去手机里面蓝牙权限观察,就能看出,外设与手机在系统层连接一直是连接着的,外设一打开蓝牙,就自动连接上手机。

WechatIMG128.jpeg

但是我们要知道,虽然系统层的连接是建立的,这时app应用与外设的连接还没有建立 ,是没有办法控制设备的,或者说,代码级别我们是没有办法去扫描到设备,控制设备,连接设备的。如果想app应用能控制设备,是需要建立app应用层连接的。

解决办法

解决思路

那么我们能不能获取到,已经与手机系统层建立起连接的所有设备呢,如果能获取到设备列表,那么,我们找到此设备,就再直接去建立app应用层的连接就可以了,刚好,SDK里面有提供了获取设备列表的方法,如下


image.png

所以,代码思路就是,先去获取已经连接设备的列表 ,如果没有连接的设备,那么就直接当作一个新外设来扫描,扫描到了,去建立应用层连接;如果有连接的设备,就直接去建立应用层的连接,下面直接上代码了

    // Mark: 开始扫描
    func startScan() {
        
        let uuid2:CBUUID = CBUUID(string: "00001000-xxxx-419b-bc43-821e71a409b7")
        
        //用于获取已连接的设备,uuid是必传参数
        let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [uuid2])
        if peripherals.count>0 {
            let temPeripheral = peripherals.first
            self.peripheral = temPeripheral
            self.peripheral.delegate = self
            centralManager.connect(self.peripheral)
            print("已经有设备连接,名称为:\(String(describing: self.peripheral.name))")
            
        } else {
            let uuid:CBUUID = CBUUID(string: "1812")
            centralManager.scanForPeripherals(withServices: [uuid], options: nil)
            print("没有设备连接")
            
        }
    }
完整代码如下:
//  ViewController.swift
//  Teleprompter_BLE
//  Created by zz on 2022/1/19.
import UIKit
import CoreBluetooth

class ViewController: UIViewController {
    
    //    var mBleTool: BleTool!
    
    //系统蓝牙设备管理对象,可以把他理解为主设备,通过他,可以去扫描和链接外设
    var centralManager: CBCentralManager!
    
    //一个全局的:CBPeripheral属性
    var peripheral:CBPeripheral!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
        //设置主设备的委托,设置完成后会执行下面的centralManagerDidUpdateState函数
        centralManager = CBCentralManager(delegate: self, queue: nil)
        
        
        //        mBleTool = BleTool(uuid: "00001000-xxxx-419b-bc43-821e71a409b7")
        //        DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
        //            let list = self.mBleTool.getConnectedDevices()
        //            print("设备连接list=\(list)")
        //
        //        }
        
        
        
    }
    
    
    // Mark: 开始扫描
    func startScan() {
        
        let uuid2:CBUUID = CBUUID(string: "00001000-xxxx-419b-bc43-821e71a409b7")
        
        //用于获取已连接的设备,uuid是必传参数
        let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [uuid2])
        if peripherals.count>0 {
            let temPeripheral = peripherals.first
            self.peripheral = temPeripheral
            self.peripheral.delegate = self
            centralManager.connect(self.peripheral)
            print("已经有设备连接,名称为:\(String(describing: self.peripheral.name))")
            
        } else {
            let uuid:CBUUID = CBUUID(string: "1812")
            centralManager.scanForPeripherals(withServices: [uuid], options: nil)
            print("没有设备连接")
            
        }
    }
    
    
}




extension ViewController: CBCentralManagerDelegate {
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        //确保本中心设备支持蓝牙低能耗(BLE)并开启时才能继续操作
        switch central.state{
        case .unknown:
            print("未知")
        case .resetting:
            print("蓝牙重置中")
        case .unsupported:
            print("本机不支持BLE")
        case .unauthorized:
            print("未授权")
        case .poweredOff:
            print("蓝牙未开启")
        case .poweredOn:
            do {
                print("蓝牙开启")
                
                startScan()
                
                
            }
        @unknown default:
            print("来自未来的错误")
        }
    }
    //MARK: didDiscover peripheral方法
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        
        print("didDiscover name:\(String(describing: peripheral.name))")
        
        //MARK: 注意点
        //如果想连接这个外设的话,一定要赋给某个变量(弄了个强引用)
        //不然系统不会把当前发现的这个外设分配给下面钩子函数里面的peripheral参数
        self.peripheral = peripheral
        
        centralManager.connect(self.peripheral, options: nil)
    }
    
    //MARK: 连接成功
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        //即将要使用peripheral的delegate方法,所以先委托self
        //寻找服务--立即(由已连接上的peripheral来)调用didDiscoverServices方法
        print("didConnect name:\(String(describing: peripheral.name))")
        
        
        //设置当前类为代理,接着去寻找外设服务,在CBPeripheralDelegate的代理方法中监听
        peripheral.delegate = self
        peripheral.discoverServices(nil)
        
        
    }
    
    //MARK: 连接失败
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        if let error = error {
            print("连接失败,原因是\(error.localizedDescription)")
        }
    }
    
    //MARK: 连接断开
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        
        if let error = error {
            print("连接失败,原因是\(error.localizedDescription)")
            
        }
        
    }
    
    
    
}


extension ViewController: CBPeripheralDelegate  {
    
    //MARK: 已发现服务(或发现失败)
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        
        if let error = error {
            
            print("没找到服务,原因是\(error.localizedDescription)")
            
        }
        
        for service in peripheral.services! {
            
            //MARK: 寻找特征--立即调用didDiscoverCharacteristicsFor方法
            peripheral.discoverCharacteristics(nil, for: service)
        }
        
    }
    
    //MARK: 发现特征(重要方法)
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if let error = error {
            print("没找到特征,原因是\(error.localizedDescription)")
        }
        
        guard let characteristics = service.characteristics else { return }
        
        for characteristic in characteristics{
            
            print("didDiscoverCharacteristicsFor\(characteristic)")
            
            //type--若需要反馈,则调用didWriteValueForCharacteristic方法
            if characteristic.properties.contains(.write){
                peripheral.writeValue("100".data(using: .utf8)!, for: characteristic, type: .withResponse)
                
            }
            
            if characteristic.properties.contains(.read){
                //读取外设的数据(其实就是读取外设里某个特征的值value)--立即调用didUpdateValueFor
                //若读取成功则可通过characteristic.value取出值
                //适合读取静态值
                peripheral.readValue(for: characteristic)
            }
            if characteristic.properties.contains(.notify){
                //订阅外设的某个数据(某个特征的值)--达到实时更新数据的目的
                //订阅后会先调用didUpdateNotificationStateFor
                //若订阅成功,则每当特征值变化时都会(若true)调用didUpdateValueFor
                //适合读动态值--一直在变化的值--如:心率
                peripheral.setNotifyValue(true, for: characteristic)
            }
            //这里可以继续发现特征下面的描述--也可不做for循环而单独指定某个特征
            //peripheral.discoverDescriptors(for: characteristic)
            //之后会立即调用didDiscoverDescriptorsFor,可在里面获取描述值
        }
        
    }
    
    //MARK: 订阅状态
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error{
            print("订阅失败,原因是\(error.localizedDescription)")
        }
        print("订阅成功")
    }
    
    //MARK: 读取(订阅)characteristic
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        
        print("didUpdateValueFor value=\(String(describing: characteristic.value))")
        
        let bytes = [UInt8](characteristic.value!)
        print(bytes)
        
        print("ANCS:\(peripheral.ancsAuthorized)")
        
        if let error = error {
            print("读取失败,原因是\(error.localizedDescription)")
        }
        
    }
    
    //MARK: 写入characteristic
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            print("写入失败,原因是\(error.localizedDescription)")
        }
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
        print("didUpdateValueFor descriptor")
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
        print("didModifyServices")
        
    }
    
}
效果如下
888.gif

彩蛋:封装工具类BleTool,获取已连接着的设备列表

999.gif

BleTool类完整代码如下

//  BLETool.swift
//  Teleprompter_BLE
//  Created by zz on 2022/1/21.
//

import Foundation
import CoreBluetooth
@objc class BleTool: NSObject {
    
    //系统蓝牙设备管理对象,可以把他理解为主设备,通过他,可以去扫描和链接外设
    var centralManager: CBCentralManager!
    
    //一个全局的:CBPeripheral属性
    var peripheral:CBPeripheral!
    
    var currentUUID:String?
    
    
    
    init(uuid:String) {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
        currentUUID = uuid
        
    }
    
    
    func getConnectedDevices() ->[[String:String]] {
        
        var desList = [[String:String]]()
        
        
        guard let tempUUID = currentUUID else {
            
            print("uuid 传过来有问题")
            return []
        }
        
        let uuid:CBUUID = CBUUID(string: tempUUID)
        //用于获取已连接的设备
        let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [uuid])
        if peripherals.count == 0 {
            print("没有连接着的设备")
            return []
        }
        print("连接着的设备数量:\(peripherals.count)")
        
        peripherals.forEach { peripheral in
            var dict = [String :String]()
            dict["id"] = peripheral.identifier.uuidString
            dict["name"] = peripheral.name
            desList.append(dict)
            
        }
        
        return desList
    }
    
    
    
    func startScan() {
        let uuid:CBUUID = CBUUID(string: "1812")
        
        centralManager.scanForPeripherals(withServices: [uuid], options: nil)
        print("开始扫描")
        
    }

    
}




extension BleTool: CBCentralManagerDelegate {
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        //确保本中心设备支持蓝牙低能耗(BLE)并开启时才能继续操作
        switch central.state{
        case .unknown:
            print("未知")
        case .resetting:
            print("蓝牙重置中")
        case .unsupported:
            print("本机不支持BLE")
        case .unauthorized:
            print("未授权")
        case .poweredOff:
            print("蓝牙未开启")
        case .poweredOn:
            do {
                print("蓝牙开启")
                
                //                startScan()
                
            }
        @unknown default:
            print("来自未来的错误")
        }
    }
    //MARK: didDiscover peripheral方法
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        
        print("didDiscover name:\(String(describing: peripheral.name))")
        
        //        let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String
        //
        //        print("name\(name)")
        
        //在这里(还未连接设备时)可以获取advertisementData和rssi
        //MARK: 注意点
        //如果想连接这个外设的话,一定要赋给某个变量(弄了个强引用)
        //不然系统不会把当前发现的这个外设分配给下面钩子函数里面的peripheral参数
        self.peripheral = peripheral
        
        centralManager.connect(self.peripheral, options: nil)
    }
    //MARK: 连接成功
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        //即将要使用peripheral的delegate方法,所以先委托self
        //寻找服务--立即(由已连接上的peripheral来)调用didDiscoverServices方法
        print("didConnect name:\(String(describing: peripheral.name))")
        
        peripheral.delegate = self
        peripheral.discoverServices(nil)
        
        
    }
    
    //MARK: 连接失败
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        if let error = error {
            print("连接失败,原因是\(error.localizedDescription)")
        }
    }
    
    //MARK: 连接断开
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        
        if let error = error {
            print("连接失败,原因是\(error.localizedDescription)")
            
        }
        
    }
    
    
    
}


extension BleTool: CBPeripheralDelegate{
    
    //MARK: 已发现服务(或发现失败)
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        
        if let error = error {
            
            print("没找到服务,原因是\(error.localizedDescription)")
            
        }
        
        for service in peripheral.services! {
            
            //MARK: 寻找特征--立即调用didDiscoverCharacteristicsFor方法
            peripheral.discoverCharacteristics(nil, for: service)
        }
        
    }
    
    //MARK: 发现特征(重要方法)
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if let error = error {
            print("没找到特征,原因是\(error.localizedDescription)")
        }
        
        guard let characteristics = service.characteristics else { return }
        
        for characteristic in characteristics{
            
            print("didDiscoverCharacteristicsFor\(characteristic)")
            
            //type--若需要反馈,则调用didWriteValueForCharacteristic方法
            if characteristic.properties.contains(.write){
                peripheral.writeValue("100".data(using: .utf8)!, for: characteristic, type: .withResponse)
                
            }
            
            if characteristic.properties.contains(.read){
                //读取外设的数据(其实就是读取外设里某个特征的值value)--立即调用didUpdateValueFor
                //若读取成功则可通过characteristic.value取出值
                //适合读取静态值
                peripheral.readValue(for: characteristic)
            }
            if characteristic.properties.contains(.notify){
                //订阅外设的某个数据(某个特征的值)--达到实时更新数据的目的
                //订阅后会先调用didUpdateNotificationStateFor
                //若订阅成功,则每当特征值变化时都会(若true)调用didUpdateValueFor
                //适合读动态值--一直在变化的值--如:心率
                peripheral.setNotifyValue(true, for: characteristic)
            }
            //这里可以继续发现特征下面的描述--也可不做for循环而单独指定某个特征
            //peripheral.discoverDescriptors(for: characteristic)
            //之后会立即调用didDiscoverDescriptorsFor,可在里面获取描述值
        }
        
    }
    
    //MARK: 订阅状态
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error{
            print("订阅失败,原因是\(error.localizedDescription)")
        }
        print("订阅成功")
    }
    
    //MARK: 读取(订阅)characteristic
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        
        print("didUpdateValueFor value=\(String(describing: characteristic.value))")
        
        let bytes = [UInt8](characteristic.value!)
        print(bytes)
        
        
        print("ANCS:\(peripheral.ancsAuthorized)")
        
        
        if let error = error {
            print("读取失败,原因是\(error.localizedDescription)")
        }
        
    }
    
    //MARK: 写入characteristic
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            print("写入失败,原因是\(error.localizedDescription)")
        }
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
        print("didUpdateValueFor descriptor")
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
        print("didModifyServices")
        
    }
    
}

调用工具类BleTool的地方,就简单清爽了,哈哈

//  ViewController.swift
//  Teleprompter_BLE
//  Created by zz on 2022/1/19.

import UIKit
import CoreBluetooth

class ViewController: UIViewController {
    
    var mBleTool: BleTool!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
        
        mBleTool = BleTool(uuid: "00001000-xxxx-419b-bc43-821e71a409b7")
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
            let list = self.mBleTool.getConnectedDevices()
            print("设备连接list=\(list)")
            
            if list.count == 0 {
                
                self.mBleTool.startScan()
            }
            
        }
        
    }
    
}

结尾

今天的分享至此接近尾声喽,小伴们,觉得有点用的话,或者已经看到这里面来的请点赞加关注吧~~ 后续分享更多物联网相关技术的文章。如果有疑问的话,欢迎在下方留言~ 新年好运!!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容