I want to use NSString to initial UIImage.But I failed.here is my code
UIImage *tImage=[UIImage imageNamed:file];//file is NSString #"1Shux.png"
if (!tImage) {
NSLog(#"%# is nil",file);
}
And Xcode log
2013-06-13 11:23:57.883 HuaHe2[3048:907] 1Shux.png is nil
But I actually add the 1Shux.png to project,and in Copy Bundle Resources,there is 1Shux.png.In addition,I use another file to initial UIImage before,and I succeed.But this time I change the image,then I failed.
I figure out the solution:delete all the files under ~/Library/Developer/Xcode/DerivedData ,then everything works well.But I don't know why.
Related
I had a main project contain more than 10 bundles. I had two image named map_bubble_right_normal, one in main bundle, the other one in sub bundle(SCommon.bundle). I write code as follow:
UIImage *image = [UIImage imageNamed:#"map_bubble_right_normal"];
The code was writen in didFinishLaunchingWithOptions of AppDelegate.
I want to load the image which I saved at main bundle. However, the result of the code that load image from sub bundle(SCommon.bundle).
I guess that image saved at main bundle maybe a error image(maybe copy problem). Therefore, I show the ipa content to see the "map_bubble_right_normal" file saved at root directory. The image is right!!!!!
I don't know why imageNamed: would load the image from sub bundle(SCommon.bundle). I tried to delete app and restart iPhone, the result is same. And, I tried to delete Derived Data of XCode, and clean the project. The image still load from sub bundles(SCommon.bundle).
Addition, I test the problem at iOS 8 and iOS 9 device.
Only a method which change the bundleId(main bundle) can solve the problem temporary so far.
I know the cache feature of UIImage, but I can't understand why did the strange scene will happen.
I sincerely request you a great god for help. Thank you~
Thank you for everyone's answer. I sorry about I had mislead all of us to bundle.
I found the cause of the problem. The Error Image isn't came from sub bundle, which came from Assets.car. The cause of the problem should be blame to Image.assert in physical directory actually. CocoaPods will copy all match "*.assets" to Assets.car.
I had made same question at Apple Developer forum, and found the key tip of the problem.
The issue of Cocoapods which relative to the problem Pods copy resource script overrides default xcasset bahaviour.
Pod_resources.sh script would copy every *.xcassets in Pod_Root if your Pod Repo had add any folder which name match *.xcassets.
Key Code of Pod_resources.sh:
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
...
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d)
while read line; do
if [[ $line != "`realpath $PODS_ROOT`*" ]]; then
XCASSET_FILES+=("$line")
fi
...
fi
Condition XCASSET_FILES will be fulfill if your Pod had add any xcassets file.
To load image from main bundle try this:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"map_bubble_right_normal" ofType:#"png"]];
If you want to load from mainBundle try this code:
NSBundle* myBundle = [NSBundle mainBundle];
NSString* myImage = [myBundle pathForResource:#"Seagull" ofType:#"jpg"];
If you want to load from sub bundle:
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"YourBundleName" ofType:#"bundle"];
NSBundle *subBundle = [NSBundle bundleWithPath:bundlePath];
NSString* myImage = [subBundle pathForResource:#"Seagull" ofType:#"jpg"];
Refer here
I've occured some same situation. Instead of two bundle you mentioned above, I failed to show the right image with the exact right name. And finally, I found the key point is that the image has a suffix of jpg instead of png. I changed to an image of png and all turned well. Maybe it's a possible situation you occured. Have a try and good luck. :)
PS: Here's a related link as a reference.
I am getting images that previously worked coming back as nil in the latest version of Xcode, nothing has changed but the image objects are coming back as null. I've tried cleaning and deleting the app, and even copied the entire folder to see if that was the issue, the folder shows up in the build phases "copy bundle resources". The folder and file names are correct, this project has been compiled and launched half a dozen times. The #2x file is also in the folder.
UIImage *iSearch = [UIImage imageNamed:#"/assets/images/controls/search_bg.png"];
UIImage *iSearchB = [UIImage imageNamed:#"/assets/images/controlsb/search_bg.png"];
NSLog(#"iSearch: %#, iSearchB: %#", iSearch, iSearchB);
Log:
2014-09-23 14:29:45.651 SmartChoice[16178:469424] iSearch: (null), iSearchB: (null)
I also have another issue where this is failing on
AppDelegate.h
return UIApplicationMain(argc, argv, nil, NSStringFromClass([IWAppDelegate class]));
Instead of the actual code on the view controller in the call stack.
//update, solved the second issue using info here, unsure why they turned that off by default: http://ijoshsmith.com/2011/11/28/debugging-exceptions-in-xcode-4-2/
You should not be using imageNamed: with a fake name with slashes to dive into a folder hierarchy. That's fragile and unsupported, and the fact that it ever worked is just chance. Don't gamble. Either use an asset catalog (far and away the best approach nowadays) or use one of the NSBundle methods that lets you specify the subdirectory, such as pathForResource:ofType:inDirectory:.
I have solved this, apparently the preceding slash, which was required before, does not work. I have changed it to [UIImage imageNamed:#"assets/images/controls/search_bg.png"]; and it works.
[UIImage imageNamed:filename]
This method returns null only on the device.
I know it's known problem and it's usually due to the fact that simulator is case insensitive.
I have tried solutions proposed here: UIImage imageNamed returns nil
But nothing worked out for me.
The case is simple: I have 4 files named:Bar#2x~ipad.png, Bar#2x~iphone.png, Bar~ipad.png, Bar~iphone.png.
All of them are in project with target checkbox checked.
NSLog(#"%#",[UIImage imageNamed:#"Bar"]);
That line of code gives me null for device and I really have no idea what I'm doing wrong right now.
I did have such a problem recently too.
After playing with filenames and paths sometimes it helps when you clean and rebuild your project.
I found myself in the same situation recently.
The solution in my case was adding the extension to the file name.
[UIImage imageNamed:#"Bar.png"]
Completely clean your build and redo it:
delete the app from the device
option-clean the whole build directory in Xcode (⌘-Shift-K)
quit xcode
delete ~/Library/Developer/Xcode/DerivedData
restart xcode, build and run
This just happened to me, and to discover was very tough: I had one image which where nil just on device
logoWhite.png
my code:
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:#"LogoWhite"] forBarMetrics:UIBarMetricsDefault];
After a while of debugging, I noticed that the name of the image is beginning with capital case letter. Obviously this doesn't matter on OSX with a ignore case file system. iOs file system isn't, so the image worked on the simulator but not on the device.
I bet that all the solutions about cleaning derived data and rebuild did randomly end with renaming the image, and this would do the trick as well. Just posting here for future reference :)
I encountered this issue and just fixed it. I listed the solution below as a reference.
I have several images, and use [UIImage imageNamed:filePath] to show them. All of images displayed well except 1 on simulator/device, but all of them can be seen on OS X. For that image, [UIImage imageNamed] always return null.
After few minutes' investigation, I found that the image cause problem is far big in file size: 4.1M. Others are all around 800kb. They have nearly same size in dimension.
Then I try to open it in image editor, then re-save it. After this, the size dropped to 800k. problem solved.
The reasons I guess,
[UIImage imageNamed:filePath] has a max file size limit? (low possibility, but need to check official document)
the image itself has some error. But OS X has better tolerance than iOS. so iOS cannot read and return null. This issue is like OS X can play more types of video files than iOS since it support more codecs.
so if you encounter this issue in the future, take a few seconds look at the file size. Hope help.
This is an odd problem, which I hadn't seen until this week.
Below are my findings, and a workaround to your problem.
In my iPhone app, I download an image and store it locally, and this had always worked fine.
But now when I run the same code, it was suddenly failing to create a UIImage out of it using the imageNamed function, and now it was returning nil.
Three notes though:
This exact code did work before, using the same source code and .png image files. I'm not sure if my copy of XCode 6.x or iOS 8.x quietly updated itself in the meantime.
The code continues to work okay (with the same image file) on the iPhone simulator. It just doesn't work on a real device.
Take a look at the code below. When UIImage:imageNamed failed, I ran some code to check if the file actually existed.. and it did. Then I loaded the binary data from the file using NSData:contentsAtPath (which also proves that the file exists and was in the right folder), then created a UIImage out of that, and it worked fine.
Huh ?!
UIImage* img = [UIImage imageNamed:backgroundImageFilename];
if (img != nil)
{
// The image loaded fine (this always worked before). Job done.
// We'll set our UIImageView "imgBackgroundView" to contain this image.
self.imgBackgroundView.image = img;
}
else
{
// We were unable to load the image file for some reason.
// Let's investigate why.
// First, I checked whether the image was actually on the device, and this returned TRUE...
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:backgroundImageFilename];
if (fileExists)
NSLog(#"Image file does exist.");
else
NSLog(#"Image file does not exist.");
// Next, I attempted to just load the bytes in the file, and amazingly, this also worked fine...
NSData *data = [[NSFileManager defaultManager] contentsAtPath:backgroundImageFilename];
if (data != nil)
{
// ..and then I COULD actually create a UIImage out of it.
img = [UIImage imageWithData:data];
if (img != nil)
{
// We have managed to load the .png file, and can now
// set our UIImageView "imgBackgroundView" to contain this image.
self.imgBackgroundView.image = img;
}
}
}
As I said, this code does provide a workaround for this problem, but it's very odd that it's suddenly started happening.
And, I should say, I did try the other suggestions in this thread, cleaning the project, removing the DerivedData, completely removing the app from the device, and so on, but they didn't make any difference.
I would be interested in knowing if anyone else hits this issue, and finds that my code sample works for them.
Update
I'm an idiot.
I'm not sure if the UIImage:imageNamed function has changed or something (and if so, why it continues to work okay on the iPhone 8.1 Simulator), but I found the following one line does work okay:
UIImage* img = [[UIImage alloc] initWithContentsOfFile:backgroundImageFilename];
So it seems as though you should use this function for loading images which aren't a part of your app's bundle.
I also have same issue then : XCode - Build Phases - Copy Bundle Resources -{see image is available or not}- add{image} - clean - delete app - Run .
I would like to add one more important point to all the above solutions
Make sure you add your image resource to right target
By mistake if Developer mess-up link with resource and target then conditions arise.
if you have multiple target then double check the resource are set to correct target.
Attached screenshot example in case of resource link between multiple targets.
I have a problem syncing NSFileWrapper documents with iCloud. I am able to create my wrapper and save it to my ubiquitous container.
When I try to read it from the device that created it, it works. When I try to read form another device that got it from iCloud, it crashes.
Some code:
This function to add a wrapper container with a NSString
- (void) addNSString:(NSString*)_string toFileWrapper:(NSFileWrapper*)_wrapper forKey:(NSString*)_key {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_string];
if(data) {
[_wrapper addRegularFileWithContents:data preferredFilename:_key];
}
}
And then here is how I decode it:
- (id) unarchiveObjectFromWrappers:(NSDictionary*)_wrappers withKey:(NSString*)_key {
id value = nil;
NSFileWrapper *wrapper = [_wrappers valueForKey:_key];
if(wrapper) {
NSData *data = [wrapper regularFileContents];
if(data) {
value = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
}
return value;
}
The decoding part works on one device and not on the others (EXC_BAD_ACCESS when the NSKeyedUnarchiver tries to unarchive from the NSData. The NSData seems good, it has the proper length and everything but when I try to log its datas for example it crashes).
My guess is that the NSFileWrapper doesn't download its full content, only its structure and that I have to do something to make it available. But I don't know what.
Any ideas?
========
Edit:
NSURLUbiquitousItemIsDownloadedKey says that the file is downloaded BUT if I try to copy it to the sandbox it fails with this error: "The operation couldn’t be completed. Bad file descriptor"
So the file is either not uploaded properly to iCloud or not downloaded properly...
It drove me crazy too. The solution is rather simple, yet totally undocumented by Apple. You must download the file specifically. Only the file wrapper is downloaded automatically, but not its contents. That's why the check says the file exists.
Before copying the file over, call something like this:
[[NSFileManager defaultManager]startDownloadingUbiquitousItemAtURL:cloudURL error:nil];
Related: Cannot sync simple text file with iCloud (bad file descriptor)
I'm using physical folders to organise my files in XCode, as I have multiple files with the same name. Eg: /skin1/navbar.jpg and /skin2/navbar.jpg.
Every time I add a new file, I can't drag it into the folder, it seems like once I ad the folder as a group in XCode, it gets locked somehow and I can't change it. When I try to initialize a UIImage with this method, it turns out to be nil.
Using this image as an example:
To create a UIImage I'm using this:
NSString *skinBasePath = [AppearanceUtils skinBasePath]; // Returns /Users/echilon/Library/Application Support/iPhone Simulator/5.1/Applications/E6C7ECF4-B36A-4092-97BC-CDE2D0A526C2/ReadMeAStory.app/ReadMeAStory/images/skin/wood/
NSString *bgImagePath = [skinBasePath stringByAppendingPathComponent:#"button_181_43.png"],
*bgImagePathPressed = [skinBasePath stringByAppendingPathComponent:#"button_181_43_pressed.png"];
UIImage *bgImage = [UIImage imageWithContentsOfFile:bgImagePath]
Everything looks fine in the debugger until I actually create the image, which comes back as null.
The full path to the image in the debugger is /Users/echilon/Library/Application Support/iPhone Simulator/5.1/Applications/E6C7ECF4-B36A-4092-97BC-CDE2D0A526C2/ReadMeAStory.app/ReadMeAStory/images/skin/wood/button_181_43.png.
What am I missing?
"images" is just a Group and not a Folder, so .../ReadMeAStory.app/ReadMeAStory/images/ don't exist.
What are you doing in [AppearanceUtils skinBasePath]?
Maybe this will help:
NSString *path=[[NSBundle mainBundle] pathForResource:#"button_181_43" ofType:#"png" inDirectory:#"skin/wood"];