#ios #swift #bluetooth #ios-bluetooth
#iOS #swift #bluetooth #ios-bluetooth
Вопрос:
Я пытаюсь отображать только имя моего устройства при сканировании. Мне нужно, чтобы в конце отображалось устройство (имя-номера) в зависимости от того, сколько устройств включено. Прямо сейчас он показывает все устройства в пределах диапазона, и я просто хочу, чтобы он показывал имя моего устройства -цифры и ничего больше. Кто-нибудь может помочь мне разобраться в этом, пожалуйста?
Вот некоторый код:
Вот первый класс, который у меня есть для сканирования.
/*function that gets called if we get a peripheral found notification*/
@objc func peripheralFound(notification: NSNotification){
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bluetoothConnection.peripherals.count
}
/*setting up a table cell which will display the name of the peripheral*/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// return a cell with the peripheral name as text in the label
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let label = cell.viewWithTag(1) as! UILabel
label.text = bluetoothConnection.peripherals[(indexPath as NSIndexPath).row].peripheral.name
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
return cell
}
/*if we select a given peripheral stop scanning for new ones. set selectedPeripheral to what we selected. try to connect to selected peripheral*/
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// the user has selected a peripheral, so stop scanning and proceed to the next view
bluetoothConnection.manager.stopScan()
selectedPeripheral = bluetoothConnection.peripherals[(indexPath as NSIndexPath).row].peripheral
bluetoothConnection.manager.connect(selectedPeripheral!, options: nil)
connectionTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(checkIfConnectSuccessful), userInfo: nil, repeats: false)
}
Вот что я делаю для другого класса.
//initialize core bluetooth
init(delegate: BluetoothClassDelegate){
super.init()
//change later
self.delegate = delegate
manager = CBCentralManager(delegate:self, queue: nil)
}
/// Start scanning for peripherals
func startScan() {
guard manager.state == .poweredOn else { return }
// start scanning for peripherals with correct service UUID
manager.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
}
/* Called when BLE turns on or off*/
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
central.scanForPeripherals(withServices: nil, options: nil)
}
else{
print("Bluetooth not available")
}
}
/* Called any time a peripheral is discovered
discovered a peripheral with the defined uuid so add it to the list of peripherals available, reorganize by RSSI, dont allow for duplicates*/
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// check whether it is a duplicate
for exisiting in peripherals {
if exisiting.peripheral.identifier == peripheral.identifier { return }
}
if peripheral.name == nil {return}
// add to the array, next sort amp; reload
let theRSSI = RSSI.floatValue
peripherals.append((peripheral: peripheral, RSSI: theRSSI))
peripherals.sort { $0.RSSI < $1.RSSI }
NotificationCenter.default.post(name: .foundPeripheral, object: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([myisscServiceUUID])
}
/* Called any time a service has been discovered for a given peripheral
we have discovered a peripheral with a matching service uuid*/
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
if service.uuid == myisscServiceUUID {
peripheral.discoverCharacteristics([myisscTxUUID, myisscRxUUID], for: service )
}
}
}
Я перепробовал много вещей, но он по-прежнему показывает мне все устройства в диапазоне Bluetooth. Могу ли я что-нибудь сделать, чтобы оно просто показывало мне уникальное имя. НАПОМИНАЮ, что мне также нужно отображать все устройства с одинаковым именем устройства, но просто разными цифрами в конце. Если бы кто-нибудь мог помочь, это было бы здорово. Спасибо.
Комментарии:
1. Не ясно, что вы пытаетесь сделать. Вы хотите ограничить обнаружение устройством определенного типа? Если это так, вам нужно отсканировать конкретную службу, которую рекламирует этот класс устройств, а не
nil
2. Да, я пытаюсь ограничить обнаружение определенным типом имени устройства. Как бы вы проверили наличие определенной службы?
3. Вам нужно знать UUID этой службы и указать его в
scanForPeripherals
вместоnil
Вы также можете проверить обнаруженное имя устройства и добавить его в массив, только если оно начинается с нужной строки имени4. Я пытался изменить его на это, и это не помогло .. /// Начать сканирование периферийных устройств с помощью функции startScan() { диспетчер охраны.состояние == .Питание от другого { возврат } // начать сканирование периферийных устройств с правильным UUID службы manager.scanForPeripherals (с сервисами: [myisscerviceuuid], опции: [CBCentralManagerScanOptionAllowDuplicatesKey: ложь]) }
5. а также это .. / * Вызывается при включении или выключении BLE */ функция centralManagerDidUpdateState(_ central: CBCentralManager) { если central.state == .PoweredOn { central.scanForPeripherals(с сервисами: [myisscerviceuuid], опции: [CBCentralManagerScanOptionAllowDuplicatesKey: false] ) } else{ печать («Bluetooth недоступен «) } }