- import SwiftUI
- import CoreBluetooth
-
- class Bluetooth: NSObject, CBCentralManagerDelegate, ObservableObject {
-
- @Published var bluetoothState = ""
- @Published var devices: [String] = []
-
- var centralManager: CBCentralManager!
-
- func start() {
- centralManager = CBCentralManager(delegate: self, queue: nil)
- }
-
- func centralManagerDidUpdateState(_ central: CBCentralManager) {
- switch central.state {
- case .unknown:
- break
- case .resetting: break
- case .unsupported: break
- case .unauthorized: break
- case .poweredOff: break
- case .poweredOn:
- centralManager.scanForPeripherals(withServices: nil)
- break
- @unknown default: break
- }
-
- bluetoothState = "\(central.state)"
- }
- public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
- print("\(peripheral)")
- self.devices.append("\(peripheral)")
- }
-
-
-
- }
-
- struct ContentView: View {
-
- @ObservedObject var tooth = Bluetooth()
-
- var body: some View {
- VStack{
- Text("状态:\(self.tooth.bluetoothState)")
- Divider()
- List{
- ForEach(self.tooth.devices,id: \.self){ item in
- Text("\(item)")
- }
- }
- }.onAppear(){ //等同于 UIKit的 viewDidAppear()
- self.tooth.start()
- }
- }
- }
-