加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

外围没有连接 – 斯威夫特

发布时间:2020-12-14 04:35:36 所属栏目:百科 来源:网络整理
导读:在我的 Swift应用程序中,我有一个应该找到蓝牙设备并连接到它的视图.蓝牙设备已开机.我能够扫描并找到该设备,然后我调用该功能连接到它,但我得不到任何反馈.我不确定为什么它无法连接. didFailToConnectPeripheral或didConnectPeripheral都没有返回任何值.
在我的 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()
    }

...

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读