草庐IT

ios - 在 SWIFT 中断开 BLE 外设

coder 2023-09-08 原文

我在断开 Swift 中的 BLE 外设时遇到了一些问题。首先,我尝试只使用 cancelPeripheralConnection: 函数。但是,如果我只是调用此函数,则永远不会调用 didDisconnectPeripheral 函数。所以我试着关注Apple's引用指南。据说,您应该在断开连接之前删除所有通知。这真的有必要吗?是否有可能一步取消所有通知?我设置了很多通知,所以我必须搜索很多服务和特性来重置它们。我想,这不可能是一个“做得很好”的解决方案。

编辑: 好吧,我发现,如果我在我的 BluetoothManager 类中调用它,cancelPeripheralConnection 工作得很好,其中 CBCentralManagerCBPeripheralDelegate 包含在内...有没有办法断开与此功能之外的外围设备的连接?

编辑 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...
}

这是我对 disconnectPeripheral 函数的实现(集成在 BluetoothManager 类中):

func disconnectPeripheral(peripheralIndex: Int)
{
    CBmanager.cancelPeripheralConnection(peripheralArray![peripheralIndex].peripheral)
}

但无论如何,如果我调用此函数,则不会调用 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...

}

最佳答案

对于您的第一个疑问,是的,我们应该在断开与外围设备的连接之前取消注册订阅的特征,原因在 Apple Documentation 中给出。 :

Note: The cancelPeripheralConnection: method is nonblocking, and any CBPeripheral class commands that are still pending to the peripheral you’re trying to disconnect may or may not finish executing. Because other apps may still have a connection to the peripheral, canceling a local connection does not guarantee that the underlying physical link is immediately disconnected. From your app’s perspective, however, the peripheral is considered disconnected, and the central manager object calls the centralManager:didDisconnectPeripheral:error: method of its delegate object.

现在,回到你的另一个问题 -

Is there a way to disconnect to a peripheral outside of this function?

您需要断开它与您实例化并开始连接的实例的连接。只要您可以在同一个对象上调用取消,它就应该可以工作。

myCentralManager.cancelPeripheralConnection(peripheral)

在我的应用程序中,我不得不使用来自许多不同类的 BLE 功能,这导致我编写了一个单例 MyBLEManager 并且所有类都将进入这个单例以进行所有 BLE 相关事件。这笔交易效果很好,有助于仅限于一个类(class)的故障排除。您可以尝试一下。

关于ios - 在 SWIFT 中断开 BLE 外设,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263483/

有关ios - 在 SWIFT 中断开 BLE 外设的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  4. ruby - ruby 乘法语句中星号中断语法前的空格 - 2

    在添加一些空格以使代码更具可读性时(与上面的代码对齐),我遇到了这个:classCdefx42endendm=C.new现在这将给出“错误数量的参数”:m.x*m.x这将给出“语法错误,意外的tSTAR,期待$end”:2/m.x*m.x这里的解析器到底发生了什么?我使用Ruby1.9.2和2.1.5进行了测试。 最佳答案 *用于运算符(42*42)和参数解包(myfun*[42,42])。当你这样做时:m.x*m.x2/m.x*m.xRuby将此解释为参数解包,而不是*运算符(即乘法)。如果您不熟悉它,参数解包(有时也称为“spl

  5. ruby - 在 ASP 页面上 Mechanize 中断 - 2

    require'mechanize'agent=Mechanize.newlogin=agent.get('http://www.schoolnet.ch/DE/HomeDE.htm')agent.clicklogin.link_withtext:/Login/然后我得到Mechanize::UnsupportedSchemeError。 最佳答案 Mechanize不支持javascript但您可以将搜索字段添加到表单并为其分配搜索词并使用mechanize提交表单form=page.forms.firstform.add_fie

  6. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  7. ruby - 可以正常中断的来自 Rake 的长时间运行的 shell 命令? - 2

    在几个项目中,我希望有一个类似rakeserver的rake任务,它将通过任何需要的方式开始为该应用程序提供服务。这是一个示例:task:serverdo%x{bundleexecrackup-p1234}end这行得通,但是当我准备停止它时,按Ctrl+c并没有正常关闭;它中断了Rake任务本身,它说rakeaborted!并给出堆栈跟踪。在某些情况下,我必须执行Ctrl+c两次。我可能可以用Signal.trap写一些东西来更优雅地中断它。有没有更简单的方法? 最佳答案 trap('SIGINT'){puts"Yourmessa

  8. ruby-on-rails - prawnto 显示新页面时不会中断的表格 - 2

    我有可变数量的表格和可变数量的行,我想让它们一个接一个地显示,但如果表格不适合当前页面,请将其放在下一页,然后继续。我已将表格放入事务中,以便我可以回滚然后打印它(如果高度适合当前页面),但我如何获得表格高度?我现在有这段代码pdf.transactiondopdf.table@data,:font_size=>12,:border_style=>:grid,:horizontal_padding=>10,:vertical_padding=>3,:border_width=>2,:position=>:left,:row_colors=>["FFFFFF","DDDDDD"]pdf.

  9. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  10. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

随机推荐