Swift   发布时间:2022-04-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了外围没有连接 – 斯威夫特大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的 Swift应用程序中,我有一个应该找到蓝牙设备并连接到它的视图.蓝牙设备已开机.我能够扫描并找到该设备,然后我调用功能连接到它,但我得不到任何反馈.我不确定为什么它无法连接.

didFailToConnectPeripheral或didConnectPeripheral都没有返回任何值.

我如何让它工作?

import UIKit
import CoreBluetooth

class 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 UIKit
import CoreBluetooth

class 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()
    }

...

}

大佬总结

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

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。