Created
April 22, 2023 09:10
-
-
Save d-date/9745e4c8a13c85a98b3f812d2299727c to your computer and use it in GitHub Desktop.
Workaround for previewing SwiftPM resources
This file contains 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
// 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