Core Location

RSS for tag

Obtain the geographic location and orientation of a device using Core Location.

Posts under Core Location tag

127 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Simulator Location Authorization Issue: Authorization Status Remains notDetermined After Denying and Changing in System Settings
Hello everyone, I'm encountering a strange location authorization issue in the iOS simulator, and I'm hoping someone can help me analyze it. Problem Description: When my app runs for the first time in the simulator, it requests location permissions. I select "Deny" for the authorization. Then, I go to the simulator's "Settings" -> "Privacy & Security" -> "Location Services" and enable location permissions for my app. However, when I return to the app, CLLocationManager.authorizationStatus still returns .notDetermined, and the authorization request pop-up does not appear again. This issue persists even after resetting the simulator settings multiple times. import CoreLocation @Observable final class LocationManager: NSObject, CLLocationManagerDelegate { var locationManager = CLLocationManager() var currentLocation: CLLocationCoordinate2D? override init() { super.init() locationManager.delegate = self } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { let status = manager.authorizationStatus print("Authorize Status: \(status)") switch status { case .authorizedWhenInUse, .authorizedAlways: locationManager.startUpdatingLocation() case .denied, .restricted: stopLocation() case .notDetermined: locationManager.requestWhenInUseAuthorization() print("Location permission not determined.") @unknown default: break } } func requestLocation() { let status = locationManager.authorizationStatus if status == .authorizedWhenInUse || status == .authorizedAlways { locationManager.requestLocation() } else { locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let newLocation = locations.first else { return } currentLocation = newLocation.coordinate print("Updated location: \(newLocation.coordinate)") } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Location update failed with error: \(error.localizedDescription)") currentLocation = nil } func stopLocation() { locationManager.stopUpdatingLocation() print("Stopped updating location") } }
0
0
438
Feb ’25
Checking Wi-Fi Status for Location Accuracy in iOS App
I am working on a duress app and would like to improve location accuracy by encouraging users to enable Wi-Fi. In Apple Maps, I noticed that when Wi-Fi is off, a dialog prompts users to turn on Wi-Fi to enhance location accuracy. I am looking to implement similar functionality in my app. Specifically, I would like to check whether Wi-Fi is enabled on the user's device (even if it is not connected to a network). Despite exploring several methods, I have been unable to determine a reliable way to check the Wi-Fi status. Can you guide me on whether it is possible to access this functionality in iOS, and if so, how I can implement it within my app?
2
0
426
Feb ’25
Underground location (in subway) doesn't update properly
We (at the NYC MTA) are building a new subway/bus app and diving deep into location tracking on iOS. We’re encountering an issue with how Core Location functions in the subway, specifically regarding how long it takes to update a passenger’s location as they travel from station to station. As an example, please see this video: https://drive.google.com/file/d/1yaddkjyPEETvTEmClPAJ2wks8b-_whqB/view?usp=sharing The red dot is set manually (via a tap gesture) and represents the ground truth of where the phone actually is at that moment. The most critical moment to observe is when the train physically arrives at a station (i.e., when I can see the platform outside my window). At this moment, I update the red dot to the center of the station on the map. Similarly, I adjust the red dot when the train departs a station, placing it just outside the station in the direction of travel. The trip shown is from Rector St to 14 St. All times are in EST. I’d like to investigate this issue further since providing a seamless underground location experience is crucial for customers. As a point of comparison, Android phones exhibit near-perfect behavior, proving that this is technically feasible. We want to ensure the iOS experience is just as smooth.
4
0
438
Feb ’25
Location not tracking in background
I really need some help. I have been going back and forth with a customer of mine for weeks. Our app is supposed to track location in the background after a user starts it in the foreground. Every time I test it, it works. I can put the app in the background and walk around for hours. Every time he tests it, it doesn't work. He puts the app into the background and about a minute later, it stops tracking him. Then it starts again when the app comes back to the foreground. We have each tried it on two devices with the same results. I'm willing to post the rest of the details if anyone is interested in helping me, but the last couple of times I got no response, so I'm not going to bother unless I can get some help this time. Thanks.
1
0
423
Feb ’25
iOS 18: startRangingBeacons Stops When Display is Off in Background (Worked on iOS 17.2.1)
Issue Summary After calling startRangingBeacons, the didRangeBeacons delegate method does not receive iBeacon scan data when the device display is turned off in the background. Expected Behavior On iOS 17.2.1 (iPhone 14), beacon ranging continues in the background even when the display is turned off. The same behavior is expected on iOS 18, but it is not working as intended. Observed Behavior On iOS 18, once the display turns off, beacon ranging stops, and the didRangeBeacons method is not triggered until the display is turned back on. • Location permission is set to “Always Allow.” • Background Modes are correctly configured (Location Updates enabled). Steps to Reproduce Ensure location permission is set to Always Allow. Enable Background Modes → Location Updates in Xcode settings. Call startRangingBeacons(in:) in the app. Put the app in the background and turn off the display. Observe that didRangeBeacons is not triggered while the display is off. Additional Notes • The issue does not occur on iOS 17.2.1 (iPhone 14), where beacon ranging continues even with the display off. • This behavior change is observed on iOS 18 across multiple devices. Could you confirm if this is an intended change in behavior or a bug? If this is expected behavior, what alternative approach is recommended to maintain continuous beacon ranging when the display is off in the background?
2
0
451
Feb ’25
iOS location recording issues iOS 18
I’m facing an issue with iOS that I hope someone can help with. I developed an app a few years ago that records GPS tracks. Up until recently, everything worked fine—even when the app was running in the background, the recording continued without problems. However, since releasing an update compiled after the iOS 18 release, users have reported that background tracking no longer works. I’ve reviewed the iOS documentation but haven’t found any relevant changes or solutions. Before the newly compiled release the app was working well on iOS 18 devices as well. Some users have reported that switching to the location permission from "When Using the App" to "Always" solved the issue. This is not the case for all users. Has anyone else encountered this issue? Any recommendations or insights on how to resolve it would be greatly appreciated. Below you can see the code used for the location tracking. Before the issue happened the app was compiled with XCode 15.4. Now I am using XCode 16.2 locationManager.activityType = CLActivityType.fitness locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = 3 locationManager.allowsBackgroundLocationUpdates = true locationManager.pausesLocationUpdatesAutomatically = false if #available(iOS 11.0, *) { locationManager.showsBackgroundLocationIndicator = true } locationManager.startUpdatingLocation() if #available(iOS 17.0, *) { // Create a CLBackgroundActivitySession object backgroundActivitySession = CLBackgroundActivitySession() } Thanks in advance for your help!
3
2
589
Feb ’25
Background location tracking not reliable
I'm writing an app in which the user is expected to initiate location tracking, let the app track for a period of time (a few minutes to a couple of hours) and then discontinue tracking. We want the user to be able to switch apps or let their device lock while tracking without losing any location updates. My understanding is that this can be done with the "While in use" location permission and does not require "Always". We don't want to have to ask our users for the "Always" permission. I'm configuring the location manager this way: locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation locationManager.allowsBackgroundLocationUpdates = true locationManager.showsBackgroundLocationIndicator = true locationManager.distanceFilter = kCLDistanceFilterNone locationManager.activityType = .otherNavigation locationManager.pausesLocationUpdatesAutomatically = false (The user is expected to be walking around in an outdoor location, stopping occasionally to take notes and pictures). I've tested this using both an iPhone and an iPad that relies on an external GPS device. It works. I can lock the device and see a continuous stream of location updates in the debugger for hours. I've also tested it while walking outdoors. However, my customer keeps reporting that the app stops tracking his location whenever it goes into the background. He says that it will track his location fine while in the foreground, but when he backgrounds it, it stops getting location updates. Then when it comes into the foreground again, it resumes. When we plot the locations on a map, you see a straight line between the place where the app went into background and where it woke up again. We know for sure that the app is just transitioning to and from the background and that it is not being terminated and restarted. I can't reproduce this result on my devices and can't figure out what I'm doing wrong. The customer says he has another app on his device (which is also an iPad with an external GPS) and that the other app does track him when it is in the background. My app does process all of the locations received in the didUpdateLocations method and not just the last one, so it's not that I'm getting the updates and ignoring them. I'm also not receiving any calls to 'locationManagerDidPauseLocationUpdates', 'didFinishDeferredUpdatesWithError', or 'didFailWithError'. The only explanation I can think of at the moment is that something changed in iOS. I know that the other app my customer is using is fairly old and built against an old version of the iOS SDK. Thanks for your help.
1
1
398
Jan ’25
Watch-Phone communication when Phone app is in background
There doesn't seem to be a background mode that will allow an iPhone app to run in the background in order to communicate with its watch app, which is running in the foreground on the watch. Have I missed something? Related but not quite the same: say the iPhone app can run in the background to get location updates. But it only wants to do so when the watch app is running. Is there a way that the watch app can wake, or even start, the iPhone app, and for the iPhone app to then enable location updates? (I have previously implemented Bluetooth background modes - I think I could achieve both of the above if I had the watch and the iPhone communicate using my own BTLE protocol, rather than using Watch Connectivity. Is this true?)
6
0
846
Feb ’25
iOS 18: “Settings” button on location permission alert does nothing, logs BUG IN CLIENT OF UIKIT warning
Hello everyone, I’m encountering a problem on the latest iOS 18 related to location permissions. When the user denies location access, my app triggers the standard system prompt asking them to enable location from Settings. On iOS 17 and below, tapping the “Settings” button in this system alert would successfully navigate the user to my app’s Settings page. However, on iOS 18, nothing happens. Instead, I see the following warning in the Xcode console: Warning : BUG IN CLIENT OF UIKIT: The caller of UIApplication.openURL(:) needs to migrate to the non-deprecated UIApplication.open(:options:completionHandler:). Force returning false (NO). Important details and context: In my own code, I have already replaced all calls to openURL(:) with open(:options:completionHandler:). I searched the entire codebase for usage of openURL: and didn’t find any. The alert that appears is the system location alert (iOS-generated), not a custom UIAlertController. Thus, I have no direct control over the underlying call. On iOS 17 (and below), tapping “Settings” in the same system dialog works perfectly and takes the user to the app’s permission page. The console message implies that somewhere—likely inside the system’s own flow—the deprecated API is being called and blocked on iOS 18. What I’ve tried: Verified I am not calling openURL: anywhere in my code. Confirmed that UIApplication.openSettingsURLString works when I programmatically open it in a custom alert. Tested multiple times on iOS 17 and iOS 18 to confirm the behavior difference. Steps to reproduce: Install the app on a device running iOS 18 Beta. Deny location permission when prompted. Trigger a piece of code that relies on location (e.g., loading a map screen) so that the OS automatically shows its standard “Location is disabled” alert, which includes a “Settings” button. Tap “Settings.” On iOS 17, this navigates to the app’s Settings. On iOS 18 Beta, it does nothing, and the console logs the BUG IN CLIENT OF UIKIT warning. Questions: Is this a known iOS 18 bug where the system’s own alert is still using the deprecated openURL: call? If so, are there any workarounds besides presenting a custom alert that manually calls open(_:options:completionHandler:)? Thank you in advance. Any guidance or confirmation would be appreciated!
1
1
931
Jan ’25
How to Reduce Geolocation Drifting Inside Buildings on iOS?
I am developing a Flutter app that uses geolocation data extensively. While the location accuracy is excellent under an open sky, I’ve noticed significant drifting when users are inside large buildings. This impacts the app’s functionality as precise location data is critical. I would like to know: Are there any specific configurations or APIs available in the Apple ecosystem to enhance indoor geolocation accuracy? Would combining GPS with other location technologies (like Wi-Fi or Bluetooth) reduce drifting effectively? Are there recommended practices for handling geolocation indoors on iOS? Any advice, examples, or guidance would be greatly appreciated!
1
0
339
Jan ’25
It's not possible to access system PTT UI when app is backgrounded and "Always" location access is activated for app
Hello. Our app uses PTT framework and "Always" location tracking at the same time. By some reason, after backgrounding app, Dynamic Island shows only location tracking icon instead if PTT icon. And when user taps on it - application foregrounding instead of system PTT UI show. Only after first incoming PTT user can access system PTT UI. Is it a bug or intended behaviour?
1
0
395
Jan ’25
The latest IOS doesn't act for the custom iBeacon anymore.
I have some questions about the changes that the latest IOS doesn't act (scanning or monitoring) for our custom beacon devices. Since about 2015, We has provided some 'location based service' by using our custom iBeacon devices. However We've just realized that the latest IOS devices doesn't work with our custom iBeacon devices. but also realized It could still work with the other normal iBeacon devices. So, I've dig this issues for a while and finally I got the answer. It's because the one byte of Ibeacon advertsing packet payload. the followings are the differences about manufacturer data part between a normal Ibeacon and our custom beacon. normal Ibeacon 0xFF 0x4C00 0x02 0x15 0x736E75685F70656F706C655F74656331 0xEA61 0x03EB 0xC5 our custom Ibeacon 0xFF 0x4C00 0x02 0x15 0x736E75685F70656F706C655F74656331 0xEA61 0x03EB 0xC5 0xDA Yes, I know. after many of searches and research, Now I've understood the byte (meaning the length of following payload) should be changed as '0x16'. But It is certainly something that has worked well not so long ago. Anyway, The introduction was so long, but this is the one question what I'd like to ask about. I need to know exactly which version of IOS this change came from. (I've tried but I couldn't find any thing about this on the official documents.) I need to expaing to my customers what's going on. for that, I need the information that exactly which version of IOS It didn't work from. Thanks in advance. Regards.
1
0
416
Jan ’25
New CoreLocation APIs
Hi All, I am currently working on an app that has some navigation functionality, and since my minimum iOS is 18 wanted to incorporate the new APIs that yield a AsyncStream of locations. I have watched both WWDC sessions, the one where the new API is introduced to retrieve the location points, and also the other video where the new authorization process for location is simplified as well. I have an app currently working in its current state, but am noticing some weird quirks when using the CLBackgroundActivitySession to get the elevated background permission. What I am doing here is to create this stream and the background object is below: return AsyncThrowingStream { continuation in let task = Task { do { for try await update in CLLocationUpdate.liveUpdates(updateType) { if shouldStopUpdate { continuation.finish() break } continuation.yield(update) } } catch { continuation.finish(throwing: error) } } state = .started(locationTask: task, background: CLBackgroundActivitySession()) } When I have an active navigation session going and am strongly holding this object and the user force quits the app (or I stop the target through Xcode) the navigation activity indicator in the status bar (or dynamic island) remains present. Even if I relaunch the app, start navigation again, and then call the invalidate method on the CLBackgroundActivitySession I then am seeing that navigation indicator even if I delete my app, and often need to do a full restart to get out of this state. Is there a step I am missing, or do I not understand the way the new API works to run in the background?
1
0
606
Jan ’25
Throttling on navigator.geolocation.getCurrentPosition on Safari
I'm using navigator.geolocation.getCurrentPosition to retrieve the users coordinates in a PWA built with Nextjs. getCurrentPosition is called by clicking on a button. If getCurrentPosition is called afterwards, the cached value is returned. On Safari, If I refresh the page, or logout, login and call getCurrentPosition again, the getCurrentPosition error callback is called with an error code 2 - POSITION_UNAVAILABLE. After around five minutes, getCurrentPosition can be called again. Is there some kind of throttling restriction on Safari navigator.geolocation.getCurrentPosition?
0
0
413
Jan ’25
Inquiry About Background Permission Issue in My App
I am writing to address a concern regarding the background permission functionality in my app, which is critical for ensuring user safety as they navigate various terrains. This feature also enables users to smoothly record their navigation tracks for review after their activities. Recently, I've noticed that this functionality is not working as seamlessly as before. Additionally, I observed that the app is not categorized under 'health and fitness'—could reclassifying it improve background activity? Before I delve into a detailed code review, I wanted to check if this issue might be related to sync or settings on the App Store side, such as permission configurations, app updates, or other related factors. Or, is it more likely an issue stemming from the app’s codebase?
1
0
439
Jan ’25
get location in app intent for interactive widgets
I have an app intent for interactive widgets. when I touch the toggle, the app intent perform to request location. func perform() async throws -> some IntentResult { var mark: LocationService.Placemark? do { mark = try await AsyncLocationServive.shared.requestLocation() print("[Widget] ConnectHandleIntent: \(mark)") } catch { WidgetHandler.shared.error = .locationUnauthorized print("[Widget] ConnectHandleIntent: \(WidgetHandler.shared.error!)") } return .result() } @available(iOSApplicationExtension 13.0, *) @available(iOS 13.0, *) final class AsyncLocationServive: NSObject, CLLocationManagerDelegate { static let shared = AsyncLocationServive() private let manager: CLLocationManager private let locationSubject: PassthroughSubject<Result<LocationService.Placemark, LocationService.Error>, Never> = .init() lazy var geocoder: CLGeocoder = { let geocoder = CLGeocoder() return geocoder }() @available(iOSApplicationExtension 14.0, *) @available(iOS 14.0, *) var isAuthorizedForWidgetUpdates: Bool { manager.isAuthorizedForWidgetUpdates } override init() { manager = CLLocationManager() super.init() manager.delegate = self } func requestLocation() async throws -> LocationService.Placemark { let result: Result<LocationService.Placemark, LocationService.Error> = try await withUnsafeThrowingContinuation { continuation in var cancellable: AnyCancellable? var didReceiveValue = false cancellable = locationSubject.sink( receiveCompletion: { _ in if !didReceiveValue { // subject completed without a value… continuation.resume(throwing: LocationService.Error.emptyLocations) } }, receiveValue: { value in // Make sure we only send a value once! guard !didReceiveValue else { return } didReceiveValue = true // Cancel current sink cancellable?.cancel() // We either got a location or an error continuation.resume(returning: value) } ) // Now that we monitor locationSubject, ask for the location DispatchQueue.global().async { self.manager.requestLocation() } } switch result { case .success(let location): // We got the location! return location case .failure(let failure): // We got an error :( throw failure } } // MARK: CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { defer { manager.stopUpdatingLocation() } guard let location = locations.first else { locationSubject.send(.failure(.emptyLocations)) return } debugPrint("[Location] location: \(location.coordinate)") manager.stopUpdatingLocation() if geocoder.isGeocoding { geocoder.cancelGeocode() } geocoder.reverseGeocodeLocation(location) { [weak self] marks, error in guard let mark = marks?.last else { self?.locationSubject.send(.failure(.emptyMarks)) return } debugPrint("[Location] mark: \(mark.description)") self?.locationSubject.send(.success(mark)) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationSubject.send(.failure(.errorMsg(error.localizedDescription))) } } I found it had not any response when the app intent performed. And there is a location logo tips in the top left corner of phone screen.
2
0
577
Jan ’25
Tracking User Activity (Driving/Walking) Periodically with Background Execution (Background state & Terminated state)
I'm working on an application where, once the user starts driving, I need to periodically check their activity every 2.5 minutes (150 seconds) to determine whether they are still driving, walking, or have stopped. If they are still driving, I want to keep rescheduling the task until the user is no longer in a driving state. Currently, I'm using startMonitoringSignificantLocationChanges to wake the app when the user's location changes, which works as expected. However, the activity detection stops after the first result is received, and I can't continue tracking the user's activity in the background (or after the app is killed from the app switcher). Here's my approach: After receiving a significant location change, I start tracking the user’s activity to check if they are driving or have stopped. I reschedule this task every 2.5 minutes as long as the user remains in a driving state. I need this process to run even when the app is in the background or terminated by the user. Question: Is it possible to keep activity detection running periodically after receiving a location change, even when the app is in the background or terminated? What is the recommended way to implement this? I would appreciate any suggestions or best practices for achieving this functionality.
1
0
562
Jan ’25
Can I ensure location is saved to SwiftData within Share Extension lifetime?
I am writing a SwiftData/SwiftUI app in which the user saves simple records, tagged with their current location. Core Location can take up to 10 seconds to retrieve the current location from its requestLocation() call. I the main app I have wrapped the CLLocationManager calls with async implementations. I kick off a Task when a new record is created, and write the location to my @Model on the main thread when it completes. A realistic use of the share extension doesn't give the task enough time to complete. I can use performExpiringActivity to complete background processing after the share extension closes but this needs to be a synchronous block. Is there some way of using performExpiringActivity when relying on a delegate callback from something like Core Location?
0
0
386
Dec ’24