'Image from bundle loads ok in SwiftUI but not in UIKit
I have developed a framework that consists of some colors in the asset catalogue. I packaged it in the cocoapod and integrated in another project where I try to access the assets from the framework. Everything works correctly as long as I'm in the SwiftUI domain, if I try to do exactly the same thing in UIKit, suddenly the images are no longer available (or at least this is what the UIImage constructor claims).
func testAssetSDKBundleAccess() {
let bundle = Assets.bundle
XCTAssertNotNil(bundle, "The Assets.bundle should not be nil")
XCTAssertNotNil(Image("Switzerland", bundle: bundle))
XCTAssertNotNil(UIImage(named: "Switzerland", in: bundle, compatibleWith: nil)) <- XCTAssertNotNil failed
}
When I run the same test case in my asset framework - it passes fine. Looks like something UIKit specific, but it got me puzzled for a couple of days now and I can't figure it out.
Xcode 13.2.1, Swift version 5
Solution 1:[1]
This turned out to be a problem connected with cocoapods. My assets framework exposes it's bundle with Assets.bundle and inside there you have to check what is available to you - when building from source you access the bundle in a different way than when using xcframework. So, our bundle access code tried one way, when it failed it tried the other. We changed the order and suddenly it started working - I don't understand why it works now but I take it. The correct order below:
public static let bundle: Bundle = {
let bundleName = "MyFramework"
/* Bundle should be present here when linked as pod dependency. */
let podBundle = Bundle(for: MyFramework.self)
if let path = podBundle.path(forResource: bundleName, ofType: "bundle"), let bundle = Bundle(path: path) {
return bundle
}
/* Bundle should be present here when running local tests or linked as xcframework. */
if let bundle = Bundle(identifier: "com.app.example.\(bundleName)") {
return bundle
}
fatalError("Unable to load bundle named \(bundleName)")
}()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lawicko |
