外围没有连接 – 斯威夫特

外围没有连接 – 斯威夫特,第1张

概述在我的 Swift应用程序中,我有一个应该找到蓝牙设备并连接到它的视图.蓝牙设备已开机.我能够扫描并找到该设备,然后我调用该功能连接到它,但我得不到任何反馈.我不确定为什么它无法连接. didFailToConnectPeripheral或didConnectPeripheral都没有返回任何值. 我如何让它工作? import UIKitimport CoreBluetoothclass 在我的 Swift应用程序中,我有一个应该找到蓝牙设备并连接到它的视图.蓝牙设备已开机.我能够扫描并找到该设备,然后我调用该功能连接到它,但我得不到任何反馈.我不确定为什么它无法连接.

dIDFailToConnectPeripheral或dIDConnectPeripheral都没有返回任何值.

我如何让它工作?

import UIKitimport CoreBluetoothclass VIEwController: UIVIEwController,CBCentralManagerDelegate,CBPeripheralDelegate {    var manager: CBCentralManager!    overrIDe func vIEwDIDLoad() {        super.vIEwDIDLoad()        manager = CBCentralManager (delegate: self,queue: nil)    }    func centralManager(central: CBCentralManager,dIDdiscoverPeripheral peripheral: CBPeripheral,advertisementData: [String : AnyObject],RSSI: NSNumber) {        print("Peripheral: \(peripheral)")        manager.connectPeripheral(peripheral,options:nil)        manager.stopScan()    }    func centralManager(central: CBCentralManager,dIDConnectPeripheral peripheral: CBPeripheral) {        print("connected!")    }    func centralManager(central: CBCentralManager,dIDdisconnectPeripheral        peripheral: CBPeripheral,error: NSError?) {            print("disconnected!")    }    func centralManager(central: CBCentralManager,dIDFailToConnectPeripheral peripheral: CBPeripheral,error: NSError?) {            print("Failed")    }    func centralManagerDIDUpdateState(central: CBCentralManager) {        print("Checking")        switch(central.state)        {        case.Unsupported:            print("BLE is not supported")        case.Unauthorized:            print("BLE is unauthorized")        case.UnkNown:            print("BLE is UnkNown")        case.resetting:            print("BLE is resetting")        case.PoweredOff:            print("BLE service is powered off")        case.PoweredOn:            print("BLE service is powered on")            print("Start Scanning")            manager.scanForperipheralsWithServices(nil,options: nil)        default:            print("default state")        }    }}
解决方法 您需要保留您尝试连接的CBPeripheral对象,否则一旦委托方法dIDdiscoverPeripheral返回它就会被释放.

import UIKitimport CoreBluetoothclass VIEwController: UIVIEwController,CBPeripheralDelegate {    var manager: CBCentralManager!    var connectingPeripheral: CBPeripheral?    overrIDe func vIEwDIDLoad() {        super.vIEwDIDLoad()        manager = CBCentralManager (delegate: self,RSSI: NSNumber) {        print("Peripheral: \(peripheral)")        self.connectingPeripheral=peripheral            manager.connectPeripheral(peripheral,options:nil)        manager.stopScan()    }...}
总结

以上是内存溢出为你收集整理的外围没有连接 – 斯威夫特全部内容,希望文章能够帮你解决外围没有连接 – 斯威夫特所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1004554.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存