IOS蓝牙没有发现外围服务。 (有时!)

时间:2015-03-14 13:04:50

标签: ios swift bluetooth

有时,我的应用程序将连接到外围设备(即" didConnectPeripheral"被调用),但它不会发现可用的服务(" didDiscoverServices"未被调用)。此外,当这种情况发生时,外围设备(基于nRF8001的Adafruit Bluefruit)会说它没有连接!这只发生在应用程序启动时间的1/5左右。

以下代码块始终执行:

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
     //Connect to the peripheral if its a UART
    if(peripheral.name == "UART") {
        currentPeripheral = peripheral
        currentPeripheral.delegate = self
        central.connectPeripheral(currentPeripheral, options: nil) 
    }
}


 func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
    println()
    println("Connected to: \(peripheral.name)")
    peripheral.discoverServices(nil)
    connectionStatus = .Connected
    central.stopScan()
    println("***Stopped scanning***")
}

知道为什么" didDiscoverServices"没被叫?

(我在iPod touch第5代上运行应用程序)

1 个答案:

答案 0 :(得分:3)

根据CoreBluetooth programming guide,你应该这样做:

  

在开始与外围设备交互之前,您应该设置   外围设备的代表,以确保它收到适当的   回调,像这样:

peripheral.delegate = self;

因此,您的didConnectPeripheral函数应如下所示:

func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
        NSLog("peripheral connected")
        peripheral.delegate = self
        peripheral.discoverServices(nil)

    }