Post

Replies

Boosts

Views

Activity

BLE Advertising
Hi, I am trying to write simple code that my iPhone acts as BLE peripheral (advertise packet). but i cannot see the advertisement on other devices that do scanning. What could be the cause? Code snippet ============= import SwiftUI import CoreBluetooth // 1. Conform to CBPeripheralManagerDelegate class BLEAdvertiser: NSObject, ObservableObject, CBPeripheralManagerDelegate { var peripheralManager: CBPeripheralManager? // 2. Start advertising func startAdvertising() { peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } // 3. CBPeripheralManagerDelegate method called when state changes func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { case .poweredOn: // Define a service UUID let serviceUUID = CBUUID(string: "1234") // Custom UUID for your service // Create a CBMutableService let service = CBMutableService(type: serviceUUID, primary: true) // Add service to the peripheral manager peripheralManager?.add(service) // Start advertising the service let advertisementData: [String: Any] = [ CBAdvertisementDataServiceUUIDsKey: [serviceUUID], CBAdvertisementDataLocalNameKey: "My iPhone" ] peripheralManager?.startAdvertising(advertisementData) print("Started advertising!") case .poweredOff: print("Bluetooth is powered off.") case .resetting: print("Bluetooth is resetting.") case .unauthorized: print("Bluetooth access is unauthorized.") case .unsupported: print("Bluetooth is unsupported on this device.") case .unknown: print("Bluetooth state is unknown.") @unknown default: print("A new state that we don’t know about.") } } // 4. Optional: Handle peripheral manager adding service func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) { if let error = error { print("Failed to add service: \(error.localizedDescription)") return } print("Service added successfully!") } } struct ContentView: View { @StateObject private var bleAdvertiser = BLEAdvertiser() var body: some View { VStack { Text("BLE Advertising") .font(.largeTitle) .padding() Button(action: { bleAdvertiser.startAdvertising() }) { Text("Start Advertising") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) } } } }
2
0
213
Oct ’24