简体   繁体   中英

How to get list of names of available bluetooth devices in ios swift?

this question is a replica of this qustion

I have declared CBCentralManagerDelegate in my class and var cb = CBCentralManager()

I set the delegate as cb.delegate = self

I search the devices as cb.scanForPeripheralsWithServices(nil, options: nil)

func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
    print("\(advertisementData.description)")
}

I am able to print the details. But in the log I get data like this:

["kCBAdvDataTxPowerLevel": 0, "kCBAdvDataLocalName": Smart Key, "kCBAdvDataManufacturerData": <bc00>, "kCBAdvDataServiceData": {
Battery = <64>;
}, "kCBAdvDataIsConnectable": 1]

All I want is the name of the device like: My2Device

Bluetooth Low Energy supports a protocol which is a bit un-intuitive if you had not experienced it before.

Think about it like that:

  • A BLE devices is called a "peripheral"
  • Each peripheral has an address (which can change on iPhones) and sometime, but not necessarily a name (which is also changeable).
  • Peripherals advertise "services"
  • Each service has "characteristics" (read/write)
  • Each characteristic has value that you can read or write

The best way to get a reliable "name" is to publish a "service" on one device and discover the service on another. If you want to go into the detail, you could also publish characteristics and read a name.

Reasoning: names are inconsistent and can change. But when you publish a service it is likely that you would discover it on the other side...

Hope this helps

By the way: if you app is use case driven and you dont want to get into the details of networking, consider using a SDK/Framework that can do that for you.

For example: http://p2pkit.io or Google Nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

Just print its name property.

 print("didDiscoverPerifpheral = \(peripheral.name)")

Or, because its an optional :

if let _name = peripheral.name {
        print("didDiscoverPerifpheral = \(peripheral.name!)")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM