3

在我的Swift應用程序中,我有一個應該找到藍牙設備並連接到它的視圖。藍牙設備已開機。我能夠掃描並找到設備,之後我會調用該功能來連接它,但我沒有收到任何反饋。我不知道爲什麼它無法連接。外設未連接 - Swift

FailToConnectPeripheral或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") 
     } 
    } 
} 
+1

您需要存儲到您所連接的屬性周邊的引用,否則將立即被釋放的委託方法'didDiscoverPeripheral'返回 – Paulw11

回答

4

您需要保留CBPeripheral對象,您試圖連接到,否則就被釋放,一旦委託方法didDiscoverPeripheral回報。

import UIKit 
import CoreBluetooth 

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate { 

    var manager: CBCentralManager! 
    var connectingPeripheral: CBPeripheral? 


    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)") 

     self.connectingPeripheral=peripheral  

     manager.connectPeripheral(peripheral, options:nil) 

     manager.stopScan() 
    } 

... 

} 
+1

謝謝soooooooooo多少保羅!!!! :) –