Added Basic Bluetooth App, which scans names of surrounding BLE devices

This commit is contained in:
severin.memmishofer
2023-07-09 15:49:35 +02:00
parent 51e1215ddf
commit a8ca380c29
3 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
//
// BluetoothViewModel.swift
// RippleChat
//
// Created by Severin Memmishofer on 09.07.23.
//
import SwiftUI
import CoreBluetooth
class BluetoothViewModel: NSObject, ObservableObject {
private var centralManager: CBCentralManager?
private var peripherals: [CBPeripheral] = []
@Published var peripheralNames: [String] = []
override init() {
super.init()
self.centralManager = CBCentralManager(delegate: self, queue: .main)
}
}
extension BluetoothViewModel: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
self.centralManager?.scanForPeripherals(withServices: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if !peripherals.contains(peripheral) {
self.peripherals.append(peripheral)
self.peripheralNames.append(peripheral.name ?? "unnamed device")
}
}
}

View File

@@ -6,8 +6,11 @@
//
import SwiftUI
import CoreBluetooth
struct ContentView: View {
@ObservedObject private var bluetoothViewModel = BluetoothViewModel()
var body: some View {
VStack {
Image(systemName: "globe")
@@ -16,6 +19,12 @@ struct ContentView: View {
Text("Hello, world!")
}
.padding()
NavigationView {
List(bluetoothViewModel.peripheralNames, id: \.self) { peripheral in
Text(peripheral)
}
.navigationTitle("Peripherals")
}
}
}