Как показать только имя вашего устройства в IOS Swift?Bluetooth (BLE) - PullRequest
0 голосов
/ 14 марта 2019

Я пытаюсь показать имя моего устройства только при сканировании.Мне нужно, чтобы показать устройство (имя-номера) в конце, в зависимости от того, сколько устройств включено.Прямо сейчас он показывает все устройства в пределах диапазона, и я просто хочу, чтобы он показывал номера моих устройств и ничего больше.Может кто-нибудь помочь мне разобраться, пожалуйста?

Вот код:

Вот первый урок для сканирования.

 /*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 & 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.Есть ли что-то, что я могу сделать, так что это просто показывает мне уникальное имя.ПОМНИТЕ, что мне также нужно показать все устройства с тем же именем устройства, но только разные номера в конце.Если бы кто-то мог помочь, это было бы здорово.Благодарю.

...