Adding CarPlay to a SwiftUI Life Cycle App

Kurt Frey - Sep 10 '21 - - Dev Community

This is a crosspost from nitricware.com

Apple makes it really easy for any developer with a Mac to create basic iOS apps. However, more complex topics sometimes require the developer to do lots of research. This is a blog post about adding a CarPlay Delegate to a SwiftUI Life Cycle App.

Currently, apps for iOS can either have the AppDelegate Life Cycle or the SwiftUI Life Cycle. While the latter poses many restrictions upon the developer, working with it is very smooth for the most part and - as you will soon see - very versatile.

Info.plist

Searching for tutorials about adding a CarPlay Delegate to an app leads to many results for AppDelegate based apps. A simple addition to Info.plist allows adding CarPlay to your SwiftUI life cycle app.

<key>UIApplicationSceneManifest</key>
    <dict>
        <key>UIApplicationSupportsMultipleScenes</key>
        <true/>
        <key>UISceneConfigurations</key>
        <dict>
            <key>CPTemplateApplicationSceneSessionRoleApplication</key>
            <array>
                <dict>
                    <key>UISceneDelegateClassName</key>
                    <string>YourAppName.CarPlaySceneDelegateName</string>
                </dict>
            </array>
        </dict>
    </dict>
Enter fullscreen mode Exit fullscreen mode

By pointing to YourAppName.CarPlaySceneDelegateName, CarPlay knows what to do.

CarPlaySceneDelegate

Of course, you actually need a class called CarPlaySceneDelegateName. It must look like this:

protocol CarPlaySceneDelegateName: UIResponder, CPTemplateApplicationSceneDelegate {
    var interfaceController: CPInterfaceController? { get set }
    func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) -> Void
    func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene, didDisconnect interfaceController: CPInterfaceController) -> Void
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . .