Added Basic Bluetooth App, which scans names of surrounding BLE devices
This commit is contained in:
35
RippleChat/BluetoothViewModel.swift
Normal file
35
RippleChat/BluetoothViewModel.swift
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user