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

Viewed 455

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.

1 Answers

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.

Related