youareawaitress
youareawaitress

Reputation: 407

Getting asset catalog path for image using UIImage(contentsOfFile:)

When you drag an image from the desktop into the asset catalog in Xcode, you can access that image in a project using:

UIImage(named: "somePNG")

But how do you access that image using UIImage(contentsOfFile:)?

if let path = Bundle.main.path(forResource: "somePNG", ofType: "png") {
    someImageView.image = UIImage(contentsOfFile: path)
}

The above code doesn't work. The image in the file inspector is added to the target. What am I missing?

Upvotes: 1

Views: 2063

Answers (2)

matt
matt

Reputation: 535315

Why would you want to use UIImage(contentsOfFile:) instead of UIImage(named:)? The reason is probably that you are wishing you could load your image from the asset catalog without automatically caching it. You can't. (I regard this as a major bug in the way asset catalogs work.) You will have to store the image at the root level of your app bundle instead, just as we used to do before asset catalogs existed.

If you name your resolution-dependent files according to the naming convention, e.g. myFile.png, [email protected], [email protected], then the right thing will happen when you use the code you've shown along with the name "myFile.png".

Upvotes: 3

Shehata Gamal
Shehata Gamal

Reputation: 100523

You can't access the image through contentsOfFile if it exists in xcassets , you need to add it to the project files , with copy option enabled

Upvotes: 1

Related Questions