Skip to content

Instantly share code, notes, and snippets.

@d-date
Created April 22, 2023 09:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-date/9745e4c8a13c85a98b3f812d2299727c to your computer and use it in GitHub Desktop.
Save d-date/9745e4c8a13c85a98b3f812d2299727c to your computer and use it in GitHub Desktop.
Workaround for previewing SwiftPM resources
// Workaround for Bundle resource when running on Xcode previews
// https://forums.swift.org/t/xcode-previews-swiftpm-resources-xcpreviewagent-crashed/51680/10
// https://developer.apple.com/forums/thread/664295?answerId=673644022#673644022
// https://gist.github.com/ctreffs/ad9d23e08d586cf75e4d1c3bb1b1061f
import class Foundation.Bundle
import class Foundation.ProcessInfo
private class BundleFinder {}
extension Foundation.Bundle {
/// Returns the resource bundle associated with the current Swift module.
static var current: Bundle = {
let bundleName = "MyLibrary_Styleguide"
var candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,
// Bundle should be present here when the package is linked into a framework.
Bundle(for: BundleFinder.self).resourceURL,
// For command-line tools.
Bundle.main.bundleURL,
]
// FIX FOR PREVIEWS
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
candidates.append(contentsOf: [
// Bundle should be present here when running previews from a different package
Bundle(for: BundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent(),
Bundle(for: BundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent()
])
}
for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
return bundle
}
}
fatalError("unable to find bundle named \(bundleName)")
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment