Pas*_*sse 3 bluetooth ios core-bluetooth bluetooth-lowenergy swift
我在Swift中断开BLE外设有一些问题.首先,我试图只使用该cancelPeripheralConnection:功能.但是,如果我只是调用此函数,didDisconnectPeripheral则永远不会调用该函数.所以我试着遵循Apple的参考指南.有人说,你应该在断开连接之前删除每个通知.这真的有必要吗?是否有可能一步取消所有通知?我设置了很多通知,因此我必须搜索许多服务和特征才能重置它们.我想,这不是一个"做得好"的解决方案.
编辑:
好的,我发现,cancelPeripheralConnection工作得很好,如果我在我的BluetoothManager课堂上调用它,在哪里CBCentralManager和CBPeripheralDelegate包括...有没有办法断开这个功能之外的外围设备?
编辑4:
import UIKit
class ValueCollectionView: UICollectionViewController
{
var valueCollectionViewCell: ValueCollectionViewCell = ValueCollectionViewCell()
var bluetoothManager: BluetoothManager = BluetoothManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "back:")
self.navigationItem.leftBarButtonItem = newBackButton;
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func back(sender: UIBarButtonItem)
{
bluetoothManager.disconnectPeripheral(selectedPeripheralIndex!)
self.navigationController?.popViewControllerAnimated(true)
}
//Some Collection View functions...
}
Run Code Online (Sandbox Code Playgroud)
这是我的disconnectPeripheral功能实现(集成在BluetoothManager类中):
func disconnectPeripheral(peripheralIndex: Int)
{
CBmanager.cancelPeripheralConnection(peripheralArray![peripheralIndex].peripheral)
}
Run Code Online (Sandbox Code Playgroud)
但无论如何,如果我调用此函数,didDisconnectPeripheral则不会调用该函数.当我将该功能放入BluetoothManager类时,例如在我发现最后一个特征之后,一切正常.
编辑5:
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
{
var CBmanager: CBCentralManager = CBCentralManager()
override init()
{
super.init()
self.CBmanager = CBCentralManager(delegate: self, queue: nil)
}
func connectPeripheral(peripheralIndex: Int)
{
CBmanager.connectPeripheral(peripheralArray![peripheralIndex].peripheral, options: nil)
}
func disconnectPeripheral(peripheralIndex: Int)
{
CBmanager.cancelPeripheralConnection(peripheralArray![peripheralIndex].peripheral)
}
//The other CentralManager functions...
}
Run Code Online (Sandbox Code Playgroud)
对于您的第一个疑问,是的,我们应该在断开外围设备之前取消注册,因为Apple文档中给出了一个原因:
注意:该
cancelPeripheralConnection:方法是非阻塞的,并且CBPeripheral仍在等待您尝试断开的外围设备的任何 类命令可能会也可能不会执行.由于其他应用程序仍可能与外围设备建立连接,因此取消本地连接并不能保证基础物理链路立即断开连接.但是,从您的应用程序的角度来看,外围设备被视为断开连接,并且中央管理器对象调用centralManager:didDisconnectPeripheral:error:其委托对象的方法.
现在,来看你的另一个问题 -
有没有办法断开此功能以外的外围设备?
您需要将其与实例化的实例断开连接并开始连接.只要你可以在同一个对象上调用取消它就可以工作.
myCentralManager.cancelPeripheralConnection(peripheral)
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我不得不使用来自许多不同类的BLE功能,这使我编写了一个单例,MyBLEManager并且所有类都来到这个单例中用于所有与BLE相关的活动.这笔交易非常有用,只能帮助排除一个课程.你可以尝试一下.
| 归档时间: |
|
| 查看次数: |
12058 次 |
| 最近记录: |