iOS 蓝牙委托(delegate)连接功能未被调用

标签 ios swift bluetooth

我正在尝试监听所有蓝牙连接/断开连接事件。即使委托(delegate)的 centralManagerDidUpdateState 函数被调用,当我连接或断开蓝牙设备时也没有任何反应。

我对出了什么问题感到困惑。我这样初始化中央管理器/委托(delegate):

var btDelegate: CBCentralManagerDelegate = BluetoothDelegate()
var btManager = CBCentralManager(delegate: btDelegate, queue: nil)

BluetoothDelegate 的定义如下:

import Foundation
import CoreBluetooth

class BluetoothDelegate : NSObject, CBCentralManagerDelegate {

    func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
        println("connect") //this line is not called
    }
    func centralManager(central: CBCentralManager!, didDisconnectPeripheral peripheral: CBPeripheral!, error: NSError!) {
        println("disconnect") //this line is not called
    }

    func centralManagerDidUpdateState(central: CBCentralManager!) {
        println("state update") //this line is called
    }
}

注意:我可以连续接收更多状态更新事件,例如当我切换蓝牙时,即使未调用连接和断开连接也是如此。

最佳答案

从您的代码看来您还没有开始扫描外围设备。通过 centralManagerDidUpdateState 方法确认您的中央处理器处于开机状态后,您应该开始扫描外围设备。

(您从蓝牙设置面板连接的蓝牙设备无关紧要。您无法访问它们。(据我所知)如果您想扫描并找出您的设备您自己的以下代码会有所帮助)

func centralManagerDidUpdateState(central: CBCentralManager!) {
  switch (central.state) {
  case CBCentralManagerState.PoweredOff:
    break
  case CBCentralManagerState.PoweredOn:
    startScan() // start scanning once the bluetooth is On
    break
  default:
    break
  }
}

你的 startScan 方法将是(你可以提供服务 UUID,如果你想要全部,请使用 nil )

func startScan(){
  if let central = btManager {
    central.scanForPeripheralsWithServices(nil, options: nil)
    println("started Scanning")
  }
}

之后,每当您发现外围设备时,didDiscoverPeripheral 方法将首先被调用。

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
  println(peripheral)
  // btManager.connectPeripheral(peripheral, options: nil)
}

从那里您收集外设,然后调用CBCentralManagerconnectPeripheral 方法。如果连接成功,将调用 didConnectPeripheral 方法。

你应该通过this documentation完整的细节

关于iOS 蓝牙委托(delegate)连接功能未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30356627/

相关文章:

python - PyBluez 'module object has no attribute ' discover_devices'

iphone - iPhone SDK 3.0 中的 GameKit

ios - Facebook iOS App 中的 Branch.io 链接

ios - 不兼容的指针类型发送 'const CFStringRef' (又名 'const struct __CFString *const' )到类型 'id' 的参数

swift - AVPlayer 视频间平滑过渡

Android:蓝牙连接、套接字和线程

ios - 为什么使用 parse.com 为 iPhone 应用程序加载文件有时真的很慢

iphone - viewDidLoad 在实例变量被赋值之前运行

ios - 检测 UITableView 部分何时滚动出 View

swift - Swift 3 AVfoundation-无法关闭相机