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
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
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)")
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.
I need some clarification on what is supposed to happen if the "allowsBackgroundLocationUpdates" flag on CLLocationManager is set to true, and only the "While in Use" permission has been given.
The customer I'm working with thinks that this combination should allow the app to receive location updates in the background indefinitely, as long as the app was in the foreground when we started receiving them.
What we've experienced is inconsistent. App updates do continue when the screen locks and in some cases when we switch to another app, but often they do not.
Our app doesn't require location updates 24/7, it requires them for a period of time when the user is performing an activity. The user starts and stops the activity in the app, and the activity might last up to a couple of hours. Can we do this using "While in Use" or do we need to request "Always" ?
when I using MKLocalSearch by japanese character
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "東京涩谷地下鉄駅"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start {....}
,it can not return the placemark,
shows Error : The operation couldn’t be completed. (MKErrorDomain error 4.). Failed to parse font key token: hiraginosans-w6
how can I fix this problem,thankyou!
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var resultsTableView: UITableView!
var mapView: MKMapView!
var searchResults = [MKMapItem]()
override func viewDidLoad() {
super.viewDidLoad()
mapView = MKMapView(frame: CGRect(x: 0, y: 220, width: view.bounds.width, height: view.bounds.height - (tabBarController?.tabBar.frame.size.height ?? 0)))
mapView.showsScale = true
mapView.showsCompass = true
mapView.showsScale = true
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
mapView.delegate = self
view.addSubview(mapView)
let selectedCoordinate = CLLocationCoordinate2D(latitude: 35.661777, longitude: 139.704051) // some Coordinate near 東京涩谷地下鉄駅
let selectedLocation = CLLocation(latitude: selectedCoordinate.latitude, longitude: selectedCoordinate.longitude)
let coordinateMKCoordinateRegion = MKCoordinateRegion(center: selectedLocation.coordinate, latitudinalMeters: 50000, longitudinalMeters:50000)
mapView.setCenter( selectedLocation.coordinate, animated: true)
mapView.setRegion(coordinateMKCoordinateRegion, animated: true)
drawCircle(radius: 5000, center: selectedLocation.coordinate)
searchForStation()
}
func drawCircle(radius: CLLocationDistance, center: CLLocationCoordinate2D) {
let circle = MKCircle(center: center, radius: radius)
mapView.addOverlay(circle)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let circleOverlay = overlay as? MKCircle {
let circleRenderer = MKCircleRenderer(circle: circleOverlay)
circleRenderer.fillColor = nil
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 2.0
return circleRenderer
}
return MKOverlayRenderer(overlay: overlay)
}
func searchForStation() {
print( "searchForStation" )
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "東京涩谷地下鉄駅" //
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { [weak self] (response, error) in
guard let self = self else { return }
guard let response = response, let mapItem = response.mapItems.first else {
print("Error : \(error?.localizedDescription ?? "Unknown error").")
return
}
for mapItem in response.mapItems {
print( "mapItem.placemark =",mapItem.placemark) // hope to get 東京涩谷地下鉄駅placemark,the value of latitudeand longitude)
}
}
}
}
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'm using apple maps to build a feature so users can create and save running/cycling/hiking routes.
Currently the map only shows trails and similar local paths after zooming in to what is basically an extreme level.
I want the trails and local paths to be more visible on a further, broader level of zoom.
APPLE MAPS JS EX:
https://trkbucket.s3.amazonaws.com/media/shoe_images/Screenshot_2024-10-23_at_10.52.17AM.png
https://trkbucket.s3.amazonaws.com/media/shoe_images/Screenshot_2024-10-23_at_10.52.04AM.png
APPLE MAPS iOS EX:
https://trkbucket.s3.amazonaws.com/media/shoe_images/IMG_9DDF5C9A320D-1.jpeg
Also strange that on iOS the path is visible while more zoomed out whereas JS does not.
Please advise how to show these map items at a broader zoom.
mapView.showsTraffic=true
mapView.showsScale=true
mapView.showsCompass=true
mapView.showsUserLocation=true
mapView.showsBuildings=true
mapView.showsLargeContentViewer=true
hi,guy,please help to see this problem,thankyou,the mapkit api support some showsfunction,but I can not find how to show the exit of subway in my own app,but the map app of appple shows the exit of the subway,so how can I show the exit of the subway stations by using mapkit
My app has been using MKLocalSearch.Request for keyword-based location searches, and it has worked smoothly for a long time. However, starting last Wednesday, I began receiving an error from MKLocalSearch.start: MKErrorDomain (error code 4).
This issue only occurs when the network environment is based in mainland China (where the API uses the Amap data source). When the network switches to other regions and other Apple Maps data source is used, the error does not occur.
Another complication is that the API doesn't always fail—certain keywords still work (for example, "Huawei").
Already filed a ticket in Feedback Assistant: https://feedbackassistant.apple.com/feedback/15544549
Is there a way to obtain the information associated to multiple places at once? For example, instead of passing a single placeID, passing an array of placeIDs, and getting the basic info such as the name, the coordinates, etc.
I’m building an iOS app using MapKit that allows users to create and navigate trails. I need offline map functionality, I was wondering if MapKit supports that. If not I was wondering if MapBox is a viable alternative to MapKit though I would prefer using MapKit. Thanks!
aoubut MKLaunchOptionsDirectionsModeKey,
when I use MKLaunchOptionsDirectionsModeTransit as a mode in my code to call function openMaps ,the apple map app launches,it has 4 mode ,subbay or ferry,bus etc,so how can I specify the subway to transit before apple map app launch,so that I do not need to select on the map app,just specific subway in my own app, then the map app auto select the subway transit navigation。now it shows two much usless route。
MKLaunchOptionsDirectionsModeDefault
MKLaunchOptionsDirectionsModeDriving
MKLaunchOptionsDirectionsModeWalking
MKLaunchOptionsDirectionsModeTransit
when I am using the mapkit navigation, I only see the 4 modes, but can not find the mode of bicycle, so how can I find the enum of using bicycle to navigate by bicycle ,than you!~
Xcode version is 16.
hi, does someone encounter this problem, this is sample code :
let request = MKDirections.Request()
request.source = MKMapItem(placemark: startPlacemark)
request.destination = MKMapItem(placemark: endPlacemark)
request.transportType = .transit // .transit does not work
I want to make a route with two point(startPlacemark and endPlacemark ), when I give request.transportType the value of **.transit ** ,I found it not work, ps: .automobile .walking works well , my Xcode version is 16 .
This is my first post here. Please guide me, if I need to provide more information to answer this post.
I write a simple application, that monitors GPS position (location). I followed Apple documentation for LiveUpdates: https://developer.apple.com/documentation/corelocation/supporting-live-updates-in-swiftui-and-mac-catalyst-apps
My app can monitor location in foreground, background or it can completely stop monitoring location. Background location, if needed, is switched on when application changes scenePhase to .background. But it is in the foreground, that memory leaks occur (according to Instruments/Leaks. Namely Leaks points to the instruction:
let updates = CLLocationUpdate.liveUpdates()
every time I start location and then stop it, by setting updatesStarted to false.
Leaks claims there are 5x leaks there:
Malloc 32 Bytes 1 0x6000002c1d00 32 Bytes libswiftDispatch.dylib OS_dispatch_queue.init(label:qos:attributes:autoreleaseFrequency:target:)
CLDispatchSilo 1 0x60000269e700 96 Bytes CoreLocation 0x184525c64
Malloc 48 Bytes 1 0x600000c8f2d0 48 Bytes Foundation +[NSString stringWithUTF8String:]
NSMutableSet 1 0x6000002c4240 32 Bytes LocationSupport 0x18baa65d4
dispatch_queue_t (serial) 1 0x600002c69c80 128 Bytes libswiftDispatch.dylib OS_dispatch_queue.init(label:qos:attributes:autoreleaseFrequency:target:)
I tried [weak self] in Task, but it doesn't solve the leaks problem and causes other issues, so I dropped it. Anyway, Apple doesn't use it either.
Just in case this is my function, which has been slightly changed comparing to Apple example, to suit my needs:
func startLocationUpdates() {
Task() {
do {
self.updatesStarted = true
let updates = CLLocationUpdate.liveUpdates()
for try await update in updates {
// End location updates by breaking out of the loop.
if !self.updatesStarted {
self.location = nil
self.mapLocation = nil
self.track.removeAll()
break
}
if let loc = update.location {
let locationCoordinate = loc.coordinate
let location2D = CLLocationCoordinate2D(latitude: locationCoordinate.latitude, longitude: locationCoordinate.longitude)
self.location = location2D
if self.isAnchor {
if #available(iOS 18.0, *) {
if !update.stationary {
self.track.append(location2D)
}
} else {
// Fallback on earlier versions
if !update.isStationary {
self.track.append(location2D)
}
}
}
}
}
} catch {
//
}
return
}
}
Can anyone help me locating these leaks?
Hi, in MapKit JS the hybrid view appears to have lost the street names overlay in the last few days. Does anyone know if this is an issue/error or a changed feature?
Thanks.
I am using the code provided on the website https://developer.apple.com/maps/sample-code/embedded-map/index.html, replacing it with my own MapKit JS Token. When accessing it using a network in mainland China, a 401 error occurs with the message [Initialization failed because the authorization token is invalid]. However, it works normally when using a network in Japan. Does this service not work in mainland China?
A north american map that allows myself and family to drop pins and with those pins upload up to a min video to share w other users. This does not have to have navigation just a basic pin drop on a live map that uploads in real-ish time to share w other users ..... i am stuck at where to start, any suggestions or has anyone already made a version they could share advice ? much appreciated