Swift - How to detect CarPlay's connect/Disconnect status in iOS app?
Asked Answered
I

2

11

I am working on a music app that supports CarPlay. Is there a way to identify if the app is connected/disconnected from the Carplay? I can't find any helpful documentation regarding this.

Any insights or documentations are greatly appreciated.

Ignatius answered 13/7, 2021 at 8:20 Comment(0)
G
0

I had the same issue as you, there is no straightforward way to tell if CarPlay started from what I read in the documentation. A work around method that I use to detect if the user started CarPlay is to use MPPlayableContentDelegate's

func playableContentManager(_ contentManager: MPPlayableContentManager, didUpdate context: MPPlayableContentManagerContext)

You can set a boolean to true the first time this is called so you can know if it is the first time or not. I know this solution isn't pretty, but it works for me. For instance, I trigger a tracking event to track when a user opens CarPlay for the first time. I am not sure what your use case is so this solution might not be ideal for you.

Here is some code, note the boolean:

class CarPlayContentManager: NSObject, MPPlayableContentDataSource, MPPlayableContentDelegate {

    private var isSetup = false

    ...

    func playableContentManager(_ contentManager: MPPlayableContentManager, didUpdate context: MPPlayableContentManagerContext) {
        
        if !isSetup {
            // Do some stuff that only happens when CarPlay is setup for the first time
            isSetup = true
        }
    }

FYI - I do not know how to detect when CarPlay is closed.

Glantz answered 20/7, 2021 at 15:29 Comment(0)
W
0

In your CPTemplateApplicationSceneDelegate implementation, this function is invoked when the device disconnects from the CarPlay screen. Note it is not invoked if the user just minimizes your CarPlay app or switches to another app.

    func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
                                  didDisconnectInterfaceController interfaceController: CPInterfaceController) {
        self.interfaceController = nil
    }
Weathersby answered 9/8, 2023 at 1:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.