Skip to content

Instantly share code, notes, and snippets.

@vnsam
Created July 29, 2021 07:30
Show Gist options
  • Save vnsam/756d24271d8ef6b735a16a6e59395adb to your computer and use it in GitHub Desktop.
Save vnsam/756d24271d8ef6b735a16a6e59395adb to your computer and use it in GitHub Desktop.
Injection III setup for SwiftUI
// SwiftUI Preview in Xcode is unreliabale and slow. So I started using InjectionIII plugin for previewing.
// AppDelegate setup
import SwiftUI
class InjectedAppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
#if DEBUG
var injectionBundlePath = "/Applications/InjectionIII.app/Contents/Resources"
#if targetEnvironment(macCatalyst)
injectionBundlePath = "\(injectionBundlePath)/macOSInjection.bundle"
#elseif os(iOS)
injectionBundlePath = "\(injectionBundlePath)/iOSInjection.bundle"
#endif
Bundle(path: injectionBundlePath)?.load()
#endif
return true
}
}
// SwiftUI App setup
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(InjectedAppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// Call site
// use this setup to inject the SwiftUI Code on save.
// Inside the preview body
class ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
#if DEBUG
@objc class func injected() {
UIApplication.shared.windows.first?.rootViewController =
UIHostingController(rootView: ContentView())
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment