Workaround for broken SwiftUI previews in macOS Frameworks

vgorloff

Vlad Gorlov

Posted on April 1, 2020

Workaround for broken SwiftUI previews in macOS Frameworks

Say you have macOS Framework project without hosting macOS Application. And you also have SwiftUI view inside that framework. Attempt to use SwiftUI preview in Xcode 11.4 will fail with an error šŸ“›.

GenericHumanReadableError: unexpected error occurred

messageRepliedWithError(
   "Connecting to launched interactive agent 53762",
   Optional(Error Domain=com.apple.dt.xcodepreviews.service Code=17 "connectToPreviewHost: Failed to connect to 53762: (null)" UserInfo={NSLocalizedDescription=connectToPreviewHost: Failed to connect to 53762: (null)})
   )
Enter fullscreen mode Exit fullscreen mode

Error while using SwiftUI preview in Xcode 11.4

Since we can use custom frameworks inside Xcode playgrounds, this means that we can also instantiate custom SwiftUI views inside playgrounds. Here is how playground code may look like.

import Foundation
import PlaygroundSupport
@testable import SwiftUI_In_macOS_Frameworks // 1ļøāƒ£ Importing custom Framework.

let view = SwiftUIView()

PlaygroundPage.current.setLiveView(view) // 2ļøāƒ£ Presenting custom SwiftUI as playground live view.
Enter fullscreen mode Exit fullscreen mode

SwiftUI preview inside Xcode Playground

āš ļø Downside: We need to recompile framework target and restart Playground preview in order to see updates. But Xcode has a shortcuts to build framework target, start and stop Playground preview āœ…. So, we can open SwiftUI view editor and Playground side by side and preview custom SwiftUI view in Playground.

Playground shortcuts

Happy coding šŸ‘‹!

Sources of the sample project can be found at GitHub.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
vgorloff
Vlad Gorlov

Posted on April 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related