I have implemented geofencing using CLMonitor.
The implementation follows this general structure:
private var monitorTask: Task<Void, Never>?
private var backgroundSession: CLBackgroundActivitySession?
func start() async {
backgroundSession = CLBackgroundActivitySession()
monitorTask = Task {
do {
let monitor = await CLMonitor("monitor")
for try await event in await monitor.events {
handleEvent(event: event)
}
} catch {}
}
}
func addSpot() async {
let monitor = await CLMonitor("monitor")
let center = CLLocationCoordinate2D(latitude: 0, longitude: 0)
let condition = CLMonitor.CircularGeographicCondition(center: center, radius: 100)
await monitor.add(condition, identifier: "sample-1")
}
When the app is not task-killed, the code inside handleEvent executes as expected.
However, after a user-initiated task kill, the functionality does not work properly.
Maps & Location
RSS for tagLearn how to integrate MapKit and Core Location to unlock the power of location-based features in your app.
Post
Replies
Boosts
Views
Activity
After upgrading to iOS 18.1, apple maps is really slow. I thought it was the app so I switched to google maps and same issue. I have tried all (including reseting the iPhone) but it did not fix it. I had iPhone 15 proMax, but since nothing worked, I upgraded to i16 but .... nothing.
Any idea on how to get it fixed?
According to the following article, the CLCircularGeographicCondition has a limit whereby only 20 conditions can be monitored by any single app.
Monitoring the user’s proximity to geographic regions
While I understand the rationale behind this limit, 20 conditions seems quite low for some apps. It would be good if an app could request that the user opt-in to allowing more conditions if they understand the impact this might have on the battery etc.
I'm migrating an app presently to use CLCircularGeographicCondition instead of the now deprecated CLCircularRegion. It would be good if there were more guidance on how to use the new Core Location API's to monitor how many conditions are in use within an app and how they can be deactivated when no longer required, allowing the app to free up more of the 20 conditions available.
I'm wondering if setting the correct activityType after initializing CLLocationManager will make the location results more accurate.
locationManager = CLLocationManager()
locationManager.distanceFilter = 20
locationManager.activityType = .fitness
When using Search.autocomplete and getting the results, each search result object has coordinate which have 13 decimal places. When you use Geocoder.reverseLookup for these coordinates, it returns the wrong address and different coordinates (6 decimal places and different as well). What works is using Geocoder.lookup (with getsUserLocation as true) and putting in the Search.autocomplete displayLines (as a string) for the query. Am I doing something wrong or is this a bug?
Code:
const exampleQuery = '<example address>';
const search = new mapkit.Search({
getsUserLocation: true,
});
search.autocomplete(
exampleQuery,
(error, data) => {
if (error) {
console.error('Search error:', error);
return;
}
const { coordinate } = data.results[0];
console.log("Autocomplete coordinate", coordinate); // Lat and lng are both have 13 decimal places
const geoCoder = new mapkit.Geocoder({});
geoCoder.reverseLookup(
new mapkit.Coordinate(coordinate.latitude, coordinate.longitude),
(error, data) => {
const { formattedAddress, coordinate } = data.results[0];
console.log(formattedAddress, coordinate); // Not the same address from example query and from the search autocomplete, also the coordinate has 7 decimal places
}
);
},
{}
);
We applied for Location Push Entitlement on June. It has been several months since then but we still got not any results (either passed or rejected).
https://developer.apple.com/documentation/applemapsserverapi/creating-and-using-tokens-with-maps-server-api
This doesn't really say what to do with .p8 private key. I know I am a noob but I really don't understand Apple Doc at all. There is no example or anything like that.
const appleMapKit = await fetch("https://maps-api.apple.com/v1/token", {
headers: {
Authorization: `Bearer ${server_api_token}`,
},
});
This is what I did but because I created the token on website, server_api_token only lasts 7 days.
So, I tried to use Profile - Key to replace that. I have .p8 file and how can I use this to create the token for the server api?
In my app, I am using geofencing to perform an action when the user enter or leaves a specified location. The geofencing (CLMonitor) is active permanently, and should work across multiple app sessions or after the device is restarted. It should also work after the app was minimized or terminated. This worked perfectly with iOS 17 and prior, but with iOS 18, things changed. As soon as iOS 18 dropped, users were informing me that the app does no longer perform the entry/exit action reliably (without me making any changes to the app). Most of the times, events are missed entirely. Sometimes, after the user opens or resumes the app, duplicate events are delivered and/or events with the current time instead of the correct time of entry/exit.
I am making sure that the app has the "Always" location permission before geofencing is enabled
The gefocence radius is between 20 and 500m, but even with the max. radius specified, the geofencing is unreliable
For the same user and geofence, the entry/exit event is delivered occasionally, but not always
I am currently not using CLLocationManager.allowsBackgroundLocationUpdates (even though it's documented as "Apps that receive location updates when running in the background must include the UIBackgroundModes key (with the location value) in their app’s Info.plist file") because it wasn't necessary on iOS 17 and in my tests, using it didn't yield any improvements
In my search for what could have caused this change, I found this WWDC video about location authorization: . It appears that with iOS 18, it is now required to have an active CLServiceSession to ensure that location updates are delivered to my app. Even though the video is long (and I've watched it multiple times), some things are still unclear. For example, the docs state:
If your app actively receives and processes location updates and terminates, it should restart those APIs upon launch in order to continue receiving updates.
Also, in the video it is stated that:
... So your job, ..., is to make sure that your process launch logic knows what features it has been tasked with pursuing, and re-takes session objects...
But on the other hand it's also said that:
you can only start holding one (a CLServiceSession) when your app is in the foreground
and also
... CLMonitor.events won’t yield results when it is not in use, unless a session which was started in the foreground, ....
To summarize my questions, for the geofencing to work as described above:
when exactly do I need to create a CLServiceSession if the app is launched into the backgorund? Immediately in the applicationDidFinishLaunching method, even though the app is still in the background (applicationState is background)? Or later on, when the app is opened again by the user, e.g. in applicationDidBecomeActive (and applicationState is active)?
do I need to specify the background mode capability as noted in the Handling location updates in the background article?
do I need to create a CLBackgroundActivitySession as noted in the Handling location updates in the background article?
does it matter, which of the four initializer methods I am using to create the CLServiceSession (with CLServiceSessionAuthorizationRequirementAlways)?
does it matter if I specify NSLocationRequireExplicitServiceSession in the Info.plist or not when I already do ensure that the app has the "Always" location permission when the feature is being enabled
Does a CLServiceSession last indefinitely and should it only be invalidated once the user disables the feature?
I started getting a location error recently. I've never seen this error before and it began happeing randomly.
Here is the breakpoint. (if let locationManager........)
var currentLocation: Result<CLLocation, Error> {
get {
#if DEBUG
return .success(CLLocation(latitude: CLLocationDegrees(exactly: 0)!, longitude: CLLocationDegrees(exactly: 0)!))
#else
if let locationManager = self.locationManager {
return locationManager.currentLocation
}
return .failure(LocationError.unknown)
#endif
}
}
I've tried everything I can think of to fix the issue. It has an issue getting the users location when logging in.
I've made no changes to the code and everything has worked for years. The bug reports show nothing. I've tried re-installing Xcode, rebuilding the pods etc.
I've tried everything that you would normally do in this situation.
I have a Map within a SwiftUI.
I initialize a variable like this:
var cameraPosition: MapCameraPosition = .userLocation(followsHeading: true, fallback: .automatic)
and then I want to zoom map, code like this:
let userRegion = MKCoordinateRegion(
center: userLocation.coordinate,
span: MKCoordinateSpan(
latitudeDelta: 0.01,
longitudeDelta: 0.01
)
)
cameraPosition = .region(userRegion)
But it does't work. How can I solve this problem?
When trying the request "hotels" on MapKitJS with searchRegionPriority=default, it will return an hotel in Ramallah even if the searchRegion is very far from there. It can happen if your search region is very broad in most place (above Europe if you zoom out a lot, over Turkey and Middle East even if the bounding box is narrower), but on specific places it happens even with a small search region (like in Tripoli, Lebanon, whatever the zoom level). With searchRegionPriority=required, many hotels can be found in the same area.
Reproduce with:
https://maps-api.apple.com/v1/search?q=hotels&searchRegion=34.45512816097114,35.849070061159864,34.428418939926146,35.80795182731595&lang=en&searchRegionPriority=default
We’re implementing a feature in our app that allows a certified MFi GPS device to act as the default location source for user positioning, replacing the internal GPS when connected. However, we’re noticing a significant discrepancy between the accuracy values reported by iOS and those directly available from the GPS device.
Here’s the issue:
When the MFi GPS is in use, it transmits standard NMEA messages (GGA, GSA, RMC, etc.) to the iOS device (providing HDOP and VDOP). However, the accuracy reported by iOS for this “location-system” seems to be less precise than what the GPS device itself reports.
For example, here are the readings we observe:
Location from iOS device (systemLocation):
Position: <+41.4, +1.8> +/- 5.00m (speed 0.05 m/s / course 329.40)
Timestamp: 6/11/24, 12:01:50 Central European Standard Time
Horizontal Accuracy (from systemLocation): 5.0 meters (16 ft)
Vertical Accuracy (from systemLocation): 9.5 meters (31 ft)
Location from GPS device directly:
Horizontal Accuracy: 9.1 ft
Vertical Accuracy: 10.3 ft
It’s evident that the accuracy values displayed by iOS differ from the values available from the GPS device, especially in terms of horizontal and vertical accuracy.
Question: Is there a known reason for this discrepancy in accuracy values? Is there a way to obtain the GPS device’s native accuracy values in iOS, or is iOS applying additional filtering or adjustments that might explain this difference? If additional filtering is applied can be disabled?
Any insights would be greatly appreciated, as accurate location reporting is critical for our app’s functionality.
Can I integrate Timer along with liveUpdates(_:) in order to manipulate the frequency. Let say for example I need the user location ever 1 min. Is it possible to do so?
I have a 2010 F-150 with an Alpine iLX-F509 receiver using CarPlay. Intermittently, and currently, the GPS shows me traveling in the opposite direction that I'm heading which makes the directions completely useless. Happens regardless of wired or wireless connection. Once I unplug from the USB or disconnect from Bluetooth, the map and directions in my iPhone 13 work normally. When plugging back in, even if I've removed the car from CarPlay and reinstall it, the problem comes back. This seems to be a problem with communication between my phone and my truck GPS. Is this a software problem with CarPlay or with the Alpine system? The firmware on the Alpine is current. Could this possibly be a problem with compatibility or my GPS antenna? I do not seem to be having the same issue with my wife's 2020 CR-V. All other features of CarPlay seem to be working fine. It's just the map and the GPS. Doesn't matter which map I use either (Apple, Google).
I encountered a crash in iOS 17 related to CLBackgroundActivitySession, which appears to be due to misleading guidance in an Apple’s WWDC video.
Crash sample code: https://github.com/steve-ham/AppleLocationCrash
Simplified Reproduction Steps:
1. Open the GitHub sample app.
2. Archive and export (Distribute App -> Custom -> (Release Testing, Enterprise, or Debugging) -> Export).
3. Open the app.
4. Tap enableBackgroundLocation -> select Allow While Using App on the system popup.
5. Tap disableBackgroundLocation.
6. Go to the iOS home screen.
7. Wait for 10 seconds.
8. Reopen the app -> crash occurs.
The crash happens because setting CLBackgroundActivitySession to nil does not end the session, despite Apple’s guidance suggesting it should. Below is the exact quote from WWDC 2023, which explicitly states that both calling invalidate() or letting the object get destroyed (i.e., setting to nil) would end the session:
WWDC 2023 Discover Streamlined Location Updates (https://developer.apple.com/videos/play/wwdc2023/10180/)
“Before starting the updates, you should instantiate a CLBackgroundActivitySession object to start a new session. Note, we are assigning the session to self.backgroundActivity, which is a property and not to a local variable. And this is important because if we used a local variable, then when it goes out of scope, the object it holds would be deallocated, invalidating the session and potentially ending your app’s access to location. Then when we want to end our session, we can do that by sending the invalidate message or by letting the object be destroyed.”
I’ve submitted this to Apple for resolution but wanted to share this with the community. This misguidance has caused issues in my app’s release. If Apple could reply to confirm or provide clarification, it would be greatly appreciated.
P.S. Even a minimal implementation in viewDidLoad triggers the crash:
let session = CLBackgroundActivitySession()
print("session (session)")
I am working with the CLBackgroundActivitySession and CLServiceSession to figure out why our app is sometimes terminated in the background.
I am unable to understand what "insufficientlyInUse" corresponds to, it could be understood as
The location data is not being used enough
the "While in use" permission is not enough
It will be very helpful if the entire enum can be explained, I am attaching the one for CLServiceSession since it is a superset of CLBackgroundActivitySession from CoreLocation
extension CLServiceSession {
public struct Diagnostic {
public var authorizationDenied: Bool { get }
public var authorizationDeniedGlobally: Bool { get }
public var authorizationRestricted: Bool { get }
public var insufficientlyInUse: Bool { get }
public var fullAccuracyDenied: Bool { get }
public var alwaysAuthorizationDenied: Bool { get }
public var serviceSessionRequired: Bool { get }
public var authorizationRequestInProgress: Bool { get }
}
...
}
Looking forward to hearing from you
Since iOS 18.1.0 I have the problem that a sheet is automatically dismissed when the system alert for the location permission is displayed. Can anyone help me?
According to WWDC sessions, the recommended approach for continuing location collection in the background with liveUpdate is by using CLBackgroundActivitySession.
In the app I’m currently developing, I call the invalidate function on the backgroundActivitySession instance when the app enters a terminated state. Then, when the app is resurrected due to startMonitoringSignificantLocationChanges, it reinitializes liveUpdate to resume location collection. When initializing CLBackgroundActivitySession, I also reinitialize the liveUpdates object to ensure the CLLocation.Updates instance is refreshed.
However, regardless of the order in which I refresh these two instances, location collection does not resume when the app is revived in the background. Should the originally created CLBackgroundActivitySession instance never be invalidated?
Any guidance on whether I am implementing this correctly would be greatly appreciated.
We create new development maps for builders and developers. Is it possible for us to add the new streets and addresses to Apple Maps so that visitors can find these brand-new streets and addresses?
I have seen examples of conducting an Indoor Survey of an IMDF where it has labels on the map.
This would help.
Our structure is basically a huge hall that gets reconfigured weekly from a horse venue to a car show to a home and garden show.
I was thinking of creating a series of walkways to criss cross the floor and then survey them once done.
It would be nice to have a label of the features on the map. How is this done?
Thank you,
Mele