Created
April 18, 2024 16:43
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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