1

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?

youareawaitress
  • 387
  • 2
  • 17

2 Answers2

3

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, myFile@2x.png, myFile@3x.png, then the right thing will happen when you use the code you've shown along with the name "myFile.png".

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • In practice, is it worth doing this to images say in a tab bar or presented once at launch? Because if the program needs more memory, it will just dump the image cache anyway and it's not like the image itself is going to disappear from the screen. Or is it smart to separate cached images from non-cached images? – youareawaitress Dec 28 '18 at 21:18
  • 2
    Wait wait. That is not the question you asked. You did not ask if it is _worth_ using `contentsOfFile:`. You asked _how_ to use `contentsOfFile:`. In reality, for something like images in a tab bar, using the asset catalog is _more_ efficient. But if you wanted to know about that, you should have asked that. (There is a WWDC 2018 video on image efficiency; I suggest you watch it.) – matt Dec 28 '18 at 21:19
  • That's why I asked it in the comment, as an aside to the main question. Well, now my question is when to use `contentsOfFile:` but I'm afraid that's not the kind of question to ask on SO so I will start my search. Watching the video now, thanks for the recommendation. – youareawaitress Dec 28 '18 at 21:21
  • The thing is that all of this has been discussed and explained thoroughly here already. You should be searching, not asking old well-travelled questions. Your question as it stands is a duplicate of these, such as https://stackoverflow.com/questions/22856283/use-xcassets-without-imagenamed-to-prevent-memory-problems, and really ought to have been shut down at the outset. – matt Dec 28 '18 at 21:23
1

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87