I am currently working on an app that uses the CLMonitor to check when the user has entered a specific region. When the user enters the region, a new region should be monitored, and the old region should be removed.
Currently, I have a startMonitoring()
method that contains the event handling logic:
func startMonitoringConditions() {
Task {
monitor = await CLMonitor(MonitorNames.monitorName)
if let identifiers = await monitor?.identifiers {
if identifiers.count == 0 {
if let coordinate = manager.location?.coordinate {
await addNewRegionAtCoordinate(coordinate: coordinate)
}
}
else {
print("Previous Monitor Region is used.")
}
}
for try await event in await monitor!.events {
if let coordinate = manager.location?.coordinate {
// do something...
await monitor!.remove(event.identifier)
await addNewRegionAtCoordinate(coordinate: coordinate)
}
}
}
}
Unfortunately, adding a new region will not update the events collection in the CLMonitor, so the new region's events will not be handled in this method.
Any help on how I could fix this problem would be greatly appreciated!
I managed to create a workaround that is poor code design but should solve the issue.
func startMonitoringConditions() {
Task {
monitor = await CLMonitor(MonitorNames.monitorName)
if let identifiers = await monitor?.identifiers {
if identifiers.count == 0 {
if let coordinate = manager.location?.coordinate {
await addNewRegionAtCoordinate(coordinate: coordinate)
}
}
else {
print("Previous Monitor Region is used.")
}
}
while continueTrackingRegions {
for try await event in await monitor!.events {
if let coordinate = manager.location?.coordinate {
// do something
await monitor!.remove(event.identifier)
await addNewRegionAtCoordinate(coordinate: coordinate)
break
}
}
}
}
}
This update seems to work for me although I am unable to fully confirm if it works 100% of the time because I am now running into an issue with the new SwiftData API. Gotta love ModelContexts...