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)")