Revisar el permiso de Bluetooth en la aplicación para iPhone https://www.jesusninoc.com/08/27/the-apps-info-plist-must-contain-an-nsbluetoothalwaysusagedescription-key-with-a-string-value-explaining-to-the-user-how-the-app-uses-this-data/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
import SwiftUI import CoreBluetooth struct ContentView: View { @StateObject private var bluetoothManager = BluetoothManager() var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Mensaje recibido: \(bluetoothManager.receivedMessage)") } .onAppear { bluetoothManager.start() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } class BluetoothManager: NSObject, ObservableObject, CBPeripheralManagerDelegate { private var peripheralManager: CBPeripheralManager? private var transferCharacteristic: CBMutableCharacteristic? @Published var receivedMessage: String = "Esperando mensaje..." override init() { super.init() peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } func start() { setupPeripheral() } func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { if peripheral.state == .poweredOn { print("Bluetooth está encendido y listo.") setupPeripheral() } else { print("Bluetooth no está disponible. Estado: \(peripheral.state.rawValue)") } } func setupPeripheral() { guard let peripheralManager = peripheralManager else { print("Error: peripheralManager no está disponible.") return } let characteristicUUID = CBUUID(string: "8667556c-9a37-4c91-84ed-54ee27d90049") transferCharacteristic = CBMutableCharacteristic( type: characteristicUUID, properties: [.write, .notify], value: nil, permissions: [.writeable] ) let serviceUUID = CBUUID(string: "d0611e78-bbb4-4591-a5f8-487910ae4366") let transferService = CBMutableService(type: serviceUUID, primary: true) transferService.characteristics = [transferCharacteristic!] peripheralManager.add(transferService) peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [serviceUUID]]) print("Anunciando el servicio con UUID: \(serviceUUID)") } func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { guard let peripheralManager = peripheralManager else { print("Error: peripheralManager no está disponible.") return } for request in requests { if let value = request.value, let stringFromData = String(data: value, encoding: .utf8) { print("Mensaje recibido: \(stringFromData)") DispatchQueue.main.async { self.receivedMessage = stringFromData } } else { print("Error: No se pudo decodificar el mensaje.") } peripheralManager.respond(to: request, withResult: .success) } } } |