iOS Development

swift – How can one use the iOS 17 CLMonitor APIs to observe for an iBeacon?

Spread the love


It appears the brand new advisable method to work with Beacons in Swift is thru a CLMonitor. As a lot as am I excited to be rid of delegate-style occasion dealing with, I can not get a fundamental instance working with the brand new type.

There appears to be very restricted documentation on the matter with the one instance being Apple’s from WWDC, which doesn’t appear to be useful for me.

My code is as follows:

import Basis
import CoreLocation

let monitorName = "BeaconMonitor"
let testBeaconId = UUID(uuidString: "EDFA3FFA-D80A-4C23-9104-11B5B0B8E8F3")!

@MainActor
public class ObservableMonitorModel: ObservableObject {
    non-public let supervisor: CLLocationManager
    
    public var monitor: CLMonitor?
    
    init() {
        self.supervisor = CLLocationManager()
        self.supervisor.requestWhenInUseAuthorization()
        self.supervisor.requestAlwaysAuthorization()
    }
    
    func startMonitoringConditions() {
        Activity {
            monitor = await CLMonitor(monitorName)
            await monitor!.add(getBeaconIdentityCondition(), identifier: "Beacon")
            
            for identifier in await monitor!.identifiers {
                guard let lastEvent = await monitor!.file(for: identifier)?.lastEvent else { proceed }
                print(identifier, lastEvent.state)
            }
            
            for strive await occasion in await monitor!.occasions {
                print("Occasion", occasion.identifier, occasion)
                
            }
        }
    }
    
}

func getBeaconIdentityCondition() -> CLMonitor.BeaconIdentityCondition {
    CLMonitor.BeaconIdentityCondition(uuid: testBeaconId)
}

Then in ContentView.swift I’ve:

struct ContentView: View {
    @ObservedObject fileprivate var locationMonitor = ObservableMonitorModel()

    var physique: some View {
        VStack {
            ...
        }.process {
            locationMonitor.startMonitoringConditions()
        }
    }
}

When ran with a spec-compliant BLE Beacon broadcasting the set UUID, the app solely outputs Beacon CLMonitoringState, not something from the for strive await loop.

I’ve tried a number of iBeacons, just like the ESP32, this Mac app, and industrial {hardware} from Amazon.

I’ve additionally tried swapping the Beacon monitor for a round geography monitor, which works positive. The app has Bluetooth and Location permissions.

Leave a Reply

Your email address will not be published. Required fields are marked *