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.
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'm building a cordova app (primarily for IOS & Android) in which the user can take an image, retake (, etc.) it and save it locally.
I'm currently struggling with the cordova cameraPlugin. So, here a short description of the problem.
When the user takes an image, it's saved locally in the apps temp folder and the user is able to view in in the UIWebView. On retaking, the image will be deleted from the temp folder and should not be available any longer (in RAM and local FS).
It works as long as the user doesn't retakes the image 2 or more times, if he does instead of the last image the first image will be referenced/rendered in WebView. After reopening the app, the image is displayed correctly.
An Example:
The user takes the first image. ==> cdv_photo_001.png
The second. ==> cdv_photo_002.png and the first one will be deleted (which seems to work correctly)
And the third. ==> cdv_photo_001.png and the second image will be deleted.
The third image will look the same as the deleted first one. This happens with every image after the third one.
It works fine after restarting the app
I've already tried to disable the App-Cache, delete the app cache before updating the image, refreshing the page and looking for answers online.
I'm getting an error when opening the camera UI, but I could not find a solution for it either.
Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before
snapshotting or snapshot after screen updates.
The code for the camera Call:
function getPhoto() {
navigator.camera.getPicture(getPhotoOnSuccess, getPhotoOnFail, {
quality: 25,
destinationType: Camera.DestinationType.FILE_URL,
correctOrientation: true,
encodingType: Camera.EncodingType.PNG
});
}
In getPhotoOnSuccess I'm basically saving the image path to a db and appending it with jQuery to the view.
And the code to delete the image: (sidenote I`m new to Objective C)
- (void) deleteImageByPath:(NSString *)imagePath withSelector:(SEL)selector{
NSError *error = nil;
NSFileManager *mgr = [NSFileManager defaultManager];
NSString *tempFolder = NSTemporaryDirectory();
if([mgr removeItemAtPath: imagePath error:&error] == NO) {
NSLog(#"File deleted");
}
//The files can be edited as well, so there can be two files in different directories
if(error != nil){
NSString *imgEl = tempFolder;
imgEl = [imgEl stringByAppendingPathComponent:imagePath.lastPathComponent];
if(![mgr removeItemAtPath:imgEl error:&error]){
NSLog(#"Old element couln't be deleted.");
}
}
[self performSelector:selector withObject:error];
}
The file is not in the directory anymore after deleting it, so I guess it works.
An important detail could be, that I wrote my own IOS cordova plugin, because the method for the file system access provided by cordova sucks.
So thats it.
The specific question is: Why and how is this happening and is there a chance to change this behavior? If yes, how should I proceed?
By the way, I`m using cordova 3.1.0 and the build target is IOS 7.
Thanks in advance.
Ok folks, I finally got it.
The whole problem was not related to my code or any of the cordova code.
So why did it happen? ==> I don't exactly know that, for it seems that this bug or whatever you might call it, has occurred to many people.
And they all tried to delete or deactivate the cache as I did, some of their problems are very close to my own but most aren't, so it took a while til I found a solution.
I read this thread and tried to append a timestamp to the image path and it worked!
My conclusion to this it, that there might be a problem with the UIWebView and the cache management.
Or it might proof as a general WebView problem, I will be able to check that in a few days on an Adroid device.
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.
[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'm trying to load a file into a string. Here is the code I'm using:
NSError *error = nil;
NSString *fullPath = [[NSBundle mainBundle] pathForResource:filename
ofType:#"html"];
NSString *text = [NSString stringWithContentsOfFile:fullPath
encoding:NSUTF8StringEncoding
error:&error];
When passed in #"about" as the filename, it works absolutely fine, showing the code works.
When passed in #"eula" as the filename, it fails with 'Cocoa error 258', which translates to NSFileReadInvalidFileNameError. However, if I swap the contents of the files over but keep the names the same, the other file fails proving there is nothing wrong with the filename, it's something to do with the content.
The about file is fairly simple HTML but the eula file is a massive mess exported from Word by the legal department.
Does anyone know of anything inside a HTML file that could cause this error to be raised?
Much thanks,
Sam
I've just spent 45 minutes with this problem, only in my case the solution was stupid and the problem slightly different.
I had a file called Playlist.txt in my resources directory. It was loading just fine.
The file was modified at one point, from within XCode.
The file stopped loading properly, with the same error as above. However, it had never been moved nor had its encoding type been changed.
I did a command-I (Get Info) on the file in the XCode directory, it told me it was UTF-8 (as expected).
I tried the "usedEncoding" way of reading files, no dice. Same error, encoding was return null.
Finally, I erased the file from XCode, dragged it in again, and did a Clean All. That fixed the problem.
This is not the first time that XCode magically caching things (incorrectly) has caused me hours and hours of wasted time. If you have an error like this which doesn't make sense, try removing and replacing files and cleaning all targets.
The error is almost certainly that your file is not in UTF-8, but you're right, that does sound like a bug in the error report.
Open the eula file up with BBEdit (or the free TextWrangler) and see what encoding it uses. Change the encoding to UTF-8 and save it. Diff the two files to see what differences have appeared. Replace the original file with the new one (fixing any glitches).
If that resolves the problem, then use the Apple Bug Reporter to report the bug in the error report.
I had the same error with you ,use file name with
[[NSBundle mainBundle] pathForResource:#"pageList" ofType:#"txt"]] good luck!
The most likely reason that +stringWithContentsOfFile:encoding:error: would fail in this case would be if you provided the wrong encoding. Are you sure that your #"eula" file is UTF8 encoded?
If you're unsure about the encoding of the file, you could always try +stringWithContentsOfFile:usedEncoding:error: instead and see if it works and what encoding it comes up with.
Don't know if this is your problem, but I just had a similar thing (stringWithContentsOfFile, no JSON), and the problem was that the file had CRLF (windows) line-endings and Western-whatever-it's-called encoding. I used SubEthaEdit to convert to LF and UTF-8, and everything works fine.
I ran into the same error.
When I played around a bit, it appeared that I was not including the file in copy bundle resources of the target.
I did that and it worked fine.
But, have to say -- error is quite misleading for such a simple cause. Just a bad guess from Xcode