Ondrej Rafaj
Ondrej Rafaj

Reputation: 4417

Loading images from assets folder from a bundle

I have a bundle with assets folder in it. I have read all the answers on stack about using UIImage(named: "drop_arrow", inBundle: bundle, compatibleWithTraitCollection: nil) (well, it's swift 3 equivalent)

path = Bundle.main.path(forResource: "LiveUI", ofType: "bundle")
if path != nil { // path with bundle is found
     let bundle: Bundle = Bundle.init(path: path!)! // bundle is there
     let image: UIImage? = UIImage(named: "HomePlayButton", in: bundle, compatibleWith: nil)
     // HomePlayButton exists in the bundle/asset folder
     // but image is nil
}

This is my project structure:

enter image description here

Can you see any problem with the code/structure of the project?

UPDATE! ... The image is set for all resolutions as universal: enter image description here

Upvotes: 11

Views: 12059

Answers (2)

TomSwift
TomSwift

Reputation: 39502

Two things to check.

1) make sure your assets bundle has an Info.plist with a bundle identifier set in it. From your screenshot it doesn't look like this is the case.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleIdentifier</key>
    <string>MyBundle</string>
</dict>
</plist>

2) Make sure your bundle has a compiled assets catalog in it. Should be named Assets.car. I don't think Xcode will just compile an Assets.xcassets folder inside a resource bundle (the bundle is effectively opaque to Xcode; likewise it wouldn't compile any .m source files you put in there). You may need a custom build step to copy the compiled Assets.car file into your assets bundle before the assets bundle is copied into the app bundle.

You can check these by finding your app bundle and right clicking on it then "Show Package Contents", then again on the contained bundle.

Manual assets compilation command:

xcrun actool Images.xcassets --compile . --platform iphoneos --minimum-deployment-target 9.0

Upvotes: 10

JAL
JAL

Reputation: 42479

Just an idea, make sure the bundle and the asset catalog in the bundle have a Target Membership property assigned to the correct target you are trying to load the images with (Utilities pane -> Target Membership):

Target Membership

It's possible that your target is able to find the bundle but not the asset catalog for some reason.

Upvotes: 0

Related Questions