How to List discoverable Bluetooth devices and alr

2019-02-17 06:28发布

问题:

I would like to include Bluetooth feature on my app using swift. I want to list all nearby/discoverable peripheral devices including those devices are already paired

Which method i should use for listing the paired devices. Im using CoreBlutooth framework for implementing Bluetooth availability check. If Bluetooth works fine i would like to list out paired devices. And if possible please provide the method for connecting the device directly from the listed paired devices

 func startUpCentralManager() {
    println("Initializing central manager")
    centralManager = CBCentralManager(delegate: self, queue: nil)


}



func centralManagerDidUpdateState(central: CBCentralManager!) {
    println("\(__LINE__) \(__FUNCTION__)")
     println("checking state")

    if central.state != .PoweredOn {
        // In a real app, you'd deal with all the states correctly
                    return
    }
    central.scanForPeripheralsWithServices(nil,options:nil)


}

//this method is not triggering

  func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {

    var localname: NSString = advertisementData[CBAdvertisementDataLocalNameKey]! as NSString

    println("Discovered\(peripheral.name)")

    if localname != " "
    {
        centralManager!.stopScan()
        //self.peripheral = peripheral
        peripheral.delegate = self
        centralManager!.connectPeripheral(peripheral, options: nil)


    }


}

is these methods are necessary to show the near by peripherals if not which methods and codes to be implemented

Thanks in Advance

回答1:

CoreBluetooth only allows you to access Bluetooth Low Energy devices. You can pair these devices if you need encryption but typically you don't.

However, there is no API to list the paired devices - you need to discover the device(s) that are offering the service you are interested in and present a list, if necessary using your own UI in your app. Once you have identified the target device you can initiate a connection.