NSString stringWithContentsOfFile failing with what seems to be the wrong error code - ios

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

Related

OpenCV 3.0 CascadeClassifier.load() Assertion Fail (!empty)

I've just updated my iOS project to version OpenCV 3.0 and whenever I try and load the haarcascade file I get an Assertion Fail.
Previous version of OpenCV works fine and there is no change to how I get the path and load the file (see below), it's just seems not to work with version 3.0
NSString *faceCascadePath = [[NSBundle mainBundle] pathForResource:kFaceCascadeFilename ofType:#"xml"];
_faceCascade.load([faceCascadePath UTF8String])
I've also attempted to amend the way I read the file (another example I found below).
const CFIndex CASCADE_NAME_LEN = 2048;
char *CASCADE_NAME = (char *) malloc(CASCADE_NAME_LEN);
CFStringGetFileSystemRepresentation( (CFStringRef)faceCascadePath, CASCADE_NAME, CASCADE_NAME_LEN);
But again to no avail...
Any suggestions would be much appreciated.
C.
Okay figured it out, I was running the "detectMultiScale" in a seperate thread and trying to load the haarcascade file in the main ViewDidLoad.
Moved the load within the thread doing the actual detection and it seemed to fix it.
Still not sure why previous versions were not effected though.

How can I change .plist entries based on my Scheme?

I have some App-Info.plist entries that need to change based on my environment. When I'm doing developmental work, they need to be one set of values, vs QA vs Production.
What would be nice is if I could simply have a script or something that runs based on the Scheme used to do the compilation.
Is this possible?
You can do it by performing some extra steps:
Duplicate [AppName]-Info.plist file by any name. Example: [AppName]-Info-dev.plist or [AppName]-Info-staging.plist etc
Map newly created .plist file in App's Target Settings. Get idea from following screenshot:
At the end, if you want to get some entry from .plist file then you need to get it like: [[[NSBundle mainBundle] infoDictionary] objectForKey:#"baseUrl"]
Project setting will automatically pick correct .plist file and give you required value.
I think msmq's answer is valid, but you should be a little careful about using the main info.plist this way. Doing that suggests that all your versions of info.plist are almost identical, except for a couple of differences. That's a recipe for divergence, and then hard-to-debug issues when you want to add a new URI handler or background mode or any of the other things that might modify info.plist.
Instead, I recommend you take the keys that vary out of the main info.plist. Create another plist (say "Config.plist") to store them. Add a Run Script build phase to copy the correct one over. See the Build Settings Reference for a list of variables you can substitute. An example script might be:
cp ${SOURCE_ROOT}/Resources/Config-${CONFIGURATION}.plist ${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Config.plist
Then you can read the file using something like this (based on Read in the Property List):
NSString *baseURL;
NSString *path = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSDictionary *dict = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListImmutable
format:NULL
errorDescription:&errorDesc];
if (dict != nil) {
baseUrl = dict[#"baseURL"];
} else {
NSAssert(#"Could not read plist: %#", errorDesc); // FIXME: Return error
}
There are other solutions of course. I personally generally use the preprocessor for this kind of problem. In my build configuration, I would set GCC_PREPROCESSOR_DEFINITIONS to include BaseURL=... for each build configuration and then in some header I would have:
#ifndef BaseURL
#define BaseURL #"http://default.example.com"
#endif
The plist way is probably clearer and easier if you have several things to set, especially if they're long or complicated (and definitely if they would need quoting). The preprocessor solution takes less code to process and has fewer failure modes (since the strings are embedded in the binary at compile time rather than read at runtime). But both are good solutions.
You can add a User-Defined-Setting in Xcode>Build-Settings, add its values according to all the schemes listed there. And then simply use that as a variable in Info plist file. That should work just fine.
This way you can avoid creating duplicate plist files, just for the sake of one or two different properties.

iCloud sync fails with "CoreData: Ubiquity: Invalid option: the value for NSPersistentStoreUbiquitousContentNameKey should not contain periods"

CoreData: Ubiquity: Invalid option: the value for NSPersistentStoreUbiquitousContentNameKey should not contain periods: com.YashwantChauhan.Outis
-PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:: CoreData: Ubiquity: mobile~20BF44C9-C39F-48DC-A8A1-B45FC82C7E20:com.YashwantChauhan.Outis
I have a problem with syncing with iCloud. These two errors above are thrown at me. I don't know what's the problem, I setup the Entitlements file, and set the Ubiquity Container to com.YashwantChauhan.Outis.
I start the CoreData stack using MagicalRecord's method:
[MagicalRecord setupCoreDataStackWithiCloudContainer:#"N6TU2CB323.com.YashwantChauhan.Outis" localStoreNamed:#"Model.sqlite"];
But that shouldn't even matter since MagicalRecord just simplifies CoreData methods.
Help much appreciated.
Ok update:
-[NSFileManager URLForUbiquityContainerIdentifier:]: An error occurred while getting ubiquity container URL: Error
Domain=LibrarianErrorDomain Code=11 "The operation couldn’t be
completed. (LibrarianErrorDomain error 11 - The requested container
identifier is not permitted by the client's
com.apple.developer.ubiquity-container-identifiers entitlement.)"
UserInfo=0x15e0d8a0 {NSDescription=The requested container identifier
is not permitted by the client's
com.apple.developer.ubiquity-container-identifiers entitlement.}
This is the latest error message I got, I realize this differs from the question's initial error but it so turns out that the old message was some kind of strange bug of sorts. I tried #Rauru Ferro's solution by removing the periods from my Ubiquity Container identifier. I knew that this wouldn't work because the requirements for the identifier is to contain periods, but then when I put the periods back in, it spat the error message above. Which makes more a lot more sense than not using periods. We all know that we do.
I also found this handy code snippet that can actually checks my Ubiquity Container identifier by fetching it. Useful snippet to quickly check if you have any problems with it.
NSString *containerId = #"com.YashwantChauhan.Outis";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *iCloudURL = [fileManager URLForUbiquityContainerIdentifier:containerId];
NSLog(#"%#", [iCloudURL absoluteString]);
Another update: By the looks of it, this stupid NSPersistentStoreUbiquitousContentNameKey should not contain periods is a whole mess. If NSPersistentStoreUbiquitousContentNameKey is created like some kind of folder (Tutorial), then the requirement is that there is no . infront of the name, like .com.YashwantChauhan.Outis but that is not the case. I am starting to go mad here! There is no problem with the Entitlements file and there is nothing with fetching the iCloud container ID in MagicalRecord. I am starting to think this is an internal problem with setting up iCloud in Xcode 5, but of course I don't know. With this said, I might just be loosing my mind over something trivial or something that will actually cause a headache for other people.
Can anybody post their Entitlements file so I can verify how an actual working version looks like. Redacted of course. Thank you!
refer
https://forums.pragprog.com/forums/252/topics/12315
Quoting the response:
This was changed recently (Mavericks). Fortunately for you, since you are just now adding iCloud, the impact is minimal.
You need to change the following line of code:
[options setValue:[[NSBundle mainBundle] bundleIdentifier] forKey:NSPersistentStoreUbiquitousContentNameKey];
To something else. What is that something else? I would recommend something descriptive to your application. I have been using class name like structures recently. So I would change it to be the name of your app perhaps or simply “DataStorage”.
The name is unique to your application so the actual value is not important as long as it is understood by you.
So I changed my code below...
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, // Key to automatically attempt to migrate versioned stores
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, // Key to attempt to create the mapping model automatically
#"TrafficCamNZ_DataStore", NSPersistentStoreUbiquitousContentNameKey, // Option to specify that a persistent store has a given name in ubiquity.
cloudURL, NSPersistentStoreUbiquitousContentURLKey, // Option to specify the log path to use for ubiquitous content logs.
nil];
Refer the line that says TrafficCamNZ_DataStore
it previously had TrafficCamNZ.DataStore
David
I am using a shared container and just had the same error warning popping up. I could fix it by replacing all occurrences of varying cloud identifier strings like:
"$(TeamIdentifierPrefix)com.mydomain.myapp" and
"com.mydomain.myapp" and
"ABCDEF0123.com.mydomain.myapp"
with just this one explicit cloud container string:
"ABCDEF0123.com.mydomain.myapp"
I guess that at some point, Xcode must have updated the entitlements and re-inserted the "$(TeamIdentifierPrefix)", which was wrong due to the shared container. Also, I had forgotten the identifer in code, just like you seemed to have:
NSString *containerId = #"com.YashwantChauhan.Outis";
that should probably be something like:
NSString *containerId = #"ABCDEF01234.com.YashwantChauhan.Outis";
I had the same issue and I am not sure what the issue is or why it is there.
From what I am reading we should be able to use the dots in the containerId.
However, for me it started working by replacing the dots in the containerId with tildes:
i.e.:
NSString *containerId = #"N6TU2CB323~com~YashwantChauhan~Outis";
instead of:
NSString *containerId = #"N6TU2CB323.com.YashwantChauhan.Outis";
Try to use comYashwantChauhanOutis, without the two points.

iOS - UIImage imageNamed: returns null on device

[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.

parsing XML located inside the project

This is the first time i'm going to parse an XML file with Xcode and it differs a bit from what I'm used to...
I read these 2 docs :
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/HandlingElements.html#//apple_ref/doc/uid/20002265-BCIJFGJI
I understand what's going on... But I still got one question. How can I do to parse an XML file which is located directly inside the project (I mean, for example in the resource file, where I usually put my images?). They usually show how to get the url of the XML file..But it's not the case here. It's going to be loaded directly on the iPad, among images and everything...
You Simply have to give the path of a local file :-
NSString *myFile= [documentsDirectory stringByAppendingPathComponent:#"youFile.xml"];
NSURL *xmlFile = [NSURL fileURLWithPath:myFile];
NSXMLParser *parser= [[NSXMLParser alloc] initWithContentsOfURL:xmlFile];
This is just an example implement your own login , use above two lines to get the path of local file.

Resources