Created
September 3, 2022 20:52
-
-
Save Frizlab/41b5e885112c3e3208e91b49424b28eb to your computer and use it in GitHub Desktop.
Workaround a Bundle Bug
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
public extension Bundle { | |
/** | |
Workaround a bug where the ``Bundle`` class is not aware of all of its bundles until it has encountered them. | |
The case happens for instance when trying to load a storyboard from a reference in a storyboard that is in another module. | |
First, an aside about module bundles. | |
A module bundle is named `<#modulename#>_<#targetname#>` and have the identifier `<#modulename#>-<#targetname#>-resources`. | |
The bundle folder name is the bundle name with the extension “`bundle`”. | |
In your module `A`, in a storyboard, you thus define a reference to another storyboard in module `B`. | |
If none of the resources in `B` have been used when the storyboard `A` is loaded, the storyboard `B` won’t be found because the bundle of the module `B` won’t be found. | |
This is probably a bug. | |
To workaround it we do something very fragile but which seems to work: | |
we instantiate a `Bundle` for all of the bundles we can find in the resource path of the current bundle and | |
ask for the bundle identifier of all the bundles. | |
It seems `Bundle` keeps a cache of the bundle identifiers to bundle paths (unverified). | |
Asking the bundle identifiers is enough to update said cache and fix the aforementioned bug. */ | |
static func makeBundleAwareOfAllOtherBundlesInResources(of bundle: Bundle) { | |
guard let rsrcURL = bundle.resourceURL, let files = try? FileManager.default.contentsOfDirectory(at: rsrcURL, includingPropertiesForKeys: nil) else { | |
return | |
} | |
for bundleURL in (files.filter{ $0.pathExtension == "bundle" }) { | |
/* This is fragile. It probably works because of a side-effect only. See this function doc for more info. */ | |
_ = Bundle(url: bundleURL)?.bundleIdentifier | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment