Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanashcraft/ff5475a4bf609ceb2a94085644358fff to your computer and use it in GitHub Desktop.
Save ryanashcraft/ff5475a4bf609ceb2a94085644358fff to your computer and use it in GitHub Desktop.
Hacky workaround to use Bundle.module with SwiftUI previews (tested with Xcode 15.3)
import Foundation
private extension Bundle {
private static let packageName = "my-package"
private static let moduleName = "MyModule"
static var swiftUIPreviewsCompatibleModule: Bundle {
final class CurrentBundleFinder {}
let isPreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
guard isPreview else {
// Not a preview, so use regular ol' Bundle.module
return .module
}
let bundleName = "\(packageName)_\(moduleName).bundle"
let simulatorProductsDirectory = Bundle(for: CurrentBundleFinder.self)
.resourceURL?
.deletingLastPathComponents(upToPathComponentWithPrefix: "Debug-")
.appendingPathComponent(bundleName)
if let bundleURL = simulatorProductsDirectory,
let bundle = Bundle(url: bundleURL)
{
return bundle
}
// Welp. This will likely crash.
return .module
}
}
private extension URL {
func deletingLastPathComponents(upToPathComponentWithPrefix prefix: String) -> URL {
var currentURL = self
while let lastPathComponent = currentURL.pathComponents.last, !lastPathComponent.hasPrefix(prefix) {
currentURL.deleteLastPathComponent()
}
return currentURL
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment