UIImage imageNamed returns nil
Asked Answered
R

20

56

I am pretty new to iOS and Xcode.

I tried to load an image with

[UIImage imageNamed:@"imageName.png/jpg and so on"];

but it only returns nil. The image should be in my project bundle, considering the fact that I can choose it from drag and drop menus in the InterfaceBuilder and it was added to Xcode via the "Add files to "projectname"..." menu.

It makes no difference whether I use .png or .jpg images, the result stays the same: they work via IB but not if I try to run the imageNamed method myself.

Roybal answered 12/6, 2012 at 14:16 Comment(7)
Select the file, and open the File Inspector pane on the right. Make sure there is a checkmark next to your target.Irritating
Have you tried cleaning your project yet? Shift-Apple-K is the command. that seemed to be the main reason I lost images.Bughouse
tried cleaning as my first idea already. Can't find any checkmark in the File Inspector, where exactly should it be?Roybal
ah, now i know what Mike Weller meant: yes there is a checkmark next to my projectRoybal
can you edit the question and put in the exact code you are using to get the image please?Neuro
It worked for me once I added the .jpg in the image name and made sure to have the @2x for retinaMirtamirth
funny, the box was checked on initial import dialog...Notogaea
D
96

There are only a few reasons why an image would come back nil with imageNamed:

  • The image is not in your bundle. Make sure the image is actually in your project. Make sure the target is checked by clicking on the file and selecting the target it belongs to.

  • You have the image name spelled incorrectly or a problem with the extension.

  • You are using a retina display but do not have an @2x image. Try changing your simulator to retina and see if it shows up.

  • If you are using an asset catalog make sure you have the correct devices selected in the attribute inspector.

Some tips:

If you are testing using simulator delete the app off of your simulator and clean your project, then re-run. If it still shows up it should show up on your phone (if it doesn't it's probably an issue with the case of the filename or the @2x version).

If you are testing on your phone and it doesn't show up, make sure you are using the same version of the simulator (if you have an iPhone 4/4s make sure to use the 4/4s simulator with retina).

One last thing according to this post: JPG image doesn't load with UIImage imageNamed There is some issue with certain JPG types working with imageNamed and no extension. IMO, you should be using PNGs anyway since iOS compresses them for you, unless you just have to use JPG.

Disgruntle answered 12/6, 2012 at 16:51 Comment(9)
Sry for my late answer - I was sick and just got back to work today. I tried rewriting and recompiling the code and suddenly it worked! I am still not exactly sure as about why it does/didn't before, but thanks a lot for all the help!Roybal
I had to delete the app, but that alone did not fix the problem. After doing product -> clean, I was able to see the correct imagesHeckman
You are 100% right! I had the same problem and it was because I didn't have the @2x file.Theodora
Haven't had any .jpg files in my bundle for like... ever? Copied one for testing purposes, lost prolly a half an hour wondering why my image wasn't loading. Up vote for bringing up the .jpg extension problem - even though I figured it out myself.Bennett
Nemesis! You're back! haha.. we've crossed paths here before.Disgruntle
I had checked all of these and they didn't work for my particular case. What worked for me was to set COMBINE_HIDPI_IMAGES to NO in the static library where the image resided. (#5665287)Tripody
It seems that iOS 7 has a problem with JPG images while iOS 8 doesn't so it happened to me and fixed it by converting the images into PNGWizened
Even after 6 years, deleting the app from the simulator was still the solution for me. Note that this also works when you encounter this using #imageLiteral in Xcode 10.Curtis
The different retina version point you made above fixed it for me. I was using a 1x resolution and that's why it wasn't showing. having a 3x one sorted it out. Thanks a lot :)Pelagias
N
20

Re Mike Weller's comment. The checkbox is ....

enter image description here

Neuro answered 12/6, 2012 at 14:27 Comment(1)
thanks a lot, found that myself after rereading the comment. It is checked though and sadly does not change the behaviour.Roybal
G
19

If you verified all of the above and are finding that your UIImage(named: "myImage") returns nil from code inside of a dynamic framework you are building, then you have to change the code to:

UIImage(named: "myImage", in: Bundle(identifier: "com.myframework.name"), compatibleWith: nil)

This should retrieve the asset from CXAssets correctly.

Greenhorn answered 23/3, 2017 at 21:58 Comment(3)
This saved my day when dealing with dynamic frameworks. I added a class method to ease out the bundle retrieval: +(NSBundle*)currentBundle { static dispatch_once_t predicate = 0; static NSBundle *myBundle = nil; dispatch_once(&predicate, ^{ myBundle = [NSBundle bundleWithIdentifier:@"yourbundle.identifier"]; }); return myBundle; }Fatalism
Is it possible to load an image like this from Interface Builder?Prisca
When using a framework compiled inside another project in Xcode, this was the only way to get the image to load when called from within the framework.Strapped
C
16

In my case, the PNG was malformed.

For some reason Xcode preview shown it correctly, but when I tried loading it with UIImage, it returned nil.

Caron answered 6/2, 2013 at 20:4 Comment(3)
You save my day! I ran into similar situation by changing image file extension from .psd to .png and expect it to work as proper png file.. Somehow Xcode lets me preview the image correctly.. That's evilBibbie
Just had the same issue. The original file was a JPEG which was re-saved as a PNG. On the simulator it worked fine but on an actual device the image would always return nil.Estrange
Thank you!! Something along these lines was the issue for me. I wouldn't say malformed for my case since the image is truly a PNG and is used everywhere else (native Android, cross-platform desktop, desktop and mobile web including iOS Safari) without issue, but UIImage kept returning nil. I opened it up in Photoshop and then exported it as a PNG overwriting the file in question and now it works. Just preposterous.Freehold
G
10

I just had this issue for jpg files named on disk "file.jpg"

I was trying to load without the extension, just @"file". While this works fine for pngs, it does not for jpg. Once I used @"file.jpg", it worked!

Gypsum answered 11/9, 2014 at 19:14 Comment(0)
S
5

Swift 5

If you get UIImage nil in dynamic framework, you should set image with bundle identifier.

You can create an extension to Bundle like this;

  • Create an extension;

    extension Bundle {
        public static let myFramework = Bundle(identifier: "com.myFramework.bundle")
    }
    
  • Then you can use like this;

    UIImage(named: "myImageName", in: Bundle.myFramework, compatibleWith: nil)
    

Or

You can use like this;

UIImage(named: "myImageName", in: Bundle(for: type(of: self)), compatibleWith: nil)

I think the first one is more useful because it's more readable than second one.

Smoodge answered 21/6, 2019 at 6:38 Comment(0)
G
2

Try re-exporting your image.

I had a similar problem, UIImage imageNamed was returning nil and none of these answers fixed my problem.

I found out that it was actually something wrong with the png file. I opened the file in GIMP image editor, saved it as a new file, exported it again as png and magically it started working.

I didn't change anything in code at all so there was definitely something wrong with the actual image file.

Godding answered 26/8, 2013 at 5:26 Comment(1)
I keep having the opposite problem, where if I export with GIMP it doesn't work. But if I export it with something else I can get it working.Vera
L
1

try

[UIImage imageNamed:@"imageName.png"];

instead (with an extension)

Livelihood answered 12/6, 2012 at 14:18 Comment(3)
@Mike Weller : Prior to iOS 4, you must specify the filename extension.Livelihood
in defence of iMx: I didn't mention trying that when I first posted the question, thought that would be to obvious ;)Roybal
@arnesomborn there are some posible reasons: linkLivelihood
B
1

I had the same problem: @"photo.jpg" resulted in 'nil' UIImage. Changing to the "actual" filespec, @"photo.JPG" works fine! I hadn't realized there was case-sensitivity there! VERY non-intuitive.

Bourguiba answered 14/5, 2013 at 3:37 Comment(0)
M
1

i had a similar issue, finally the cleanup fixed it: the image showed up in the simulator, but id did not show up when running the app on the iPhone.
What I did: 1) deleted the app from the iPhone 2) performed Product/Clean after that the bug was fixed and the image showed up!

Martella answered 1/11, 2013 at 17:7 Comment(0)
H
1

Try to use UIImage(contentsOfFile:) instead of imageNamed. It worked for me with downloaded images.

Handicap answered 30/7, 2015 at 2:13 Comment(0)
S
1

Check that file has no space at the end. The name like name @2x.png will fail loading, but [email protected] is fine

Selfcontained answered 4/3, 2016 at 13:13 Comment(0)
N
0

Does the image work on the simulator but not on the device?

If so, in this scenario it is always to do with the case of the name. The device requires exact case and the simulator is not so fussy if I remember correctly.

e.g. for an image named image.png

[UIImage imageNamed:@"Image"];

would work on the simulator but not on the device...

Neuro answered 12/6, 2012 at 14:58 Comment(1)
That's not because the simulator is less fuzzy but because by default HFS+ (the OS X file system) is case-insensitive. That means it considers aa, AA, aA, and Aa to be the same file. You can format a new HD with HFS+ and decide to make it case-sensitive (Disk Utility gives you that choice) but Macs ship with a pre-formatted HD that is never case-sensitive. Many Mac programmers pay no attention and then their app will break on Macs whose owner re-formatted their HD to be case sensitive; which is possible if you re-install your system from scratch.Dibru
S
0

Make sure you have the image for the DEVICE you are using in your .xcassets file. An image flagged for iPad won't show up on the phone (or the simulated phone).

Sanjuanitasank answered 28/8, 2014 at 23:3 Comment(0)
E
0

In addition to @Inturbidus's answer: For those who came here working on Application Extensions:

The image you are working with should belongs to both targets - hosted app and extension.

In other case you'll always getting nil trying to access it from within the extension's code.

Ethelinda answered 2/9, 2015 at 9:36 Comment(0)
P
0

For Xcode 6.4, click on Images.xcassets and check whether there are entries for each image that you called. You may right-click on the image and select "Show in Finder" to check if the images are the correct ones added.

Peggiepeggir answered 11/9, 2015 at 18:47 Comment(0)
B
0

Make sure the Attributes Inspector name field of the image matches exactly the name you're using. In my case the image was part of a folder and so the image name was "folder/name". Using this long name solved the problem. XCode 7.3.1

Blah answered 6/9, 2016 at 21:19 Comment(0)
F
0

In my case, using a name with accented characters proved to be a poor idea. I changed Astéroïdes to Asteroids and it worked fine.

Fredi answered 24/4, 2017 at 13:22 Comment(0)
R
0

In my case problem was with image name in asset catalog. For example if you have image with name "TEst" and change name to "Test", changes won't be indexed. If your teammate will pull commit with this changes, image in his asset catalog will have previous name "TEst". Very small chance to catch this situation but it's possible.

Renault answered 24/1, 2020 at 12:25 Comment(0)
R
0

I had multiple .xcassets in my projects and 2 had duplicate name of images. So it was not loading the image in my case.

Rebuff answered 10/2, 2020 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.