Problem reading file using stringWithContentsOfFile: - objective-c

In my app I have to read an XML file and display it in a UITextView. To do this I tried the code below. This code is resulting in a crash; can any one tell me the exact mistake? I hope I wrote well. Please help me out. Thank you.
-(IBAction)xmlParse{
NSString *xmlPath=[[[[UIApplication sharedApplication]delegate] applicationDocumentDirectory]stringByAppendingPathComponent:#"xmlFile/toc.xml"];
NSError *error=nil;
NSString *fileContent=[NSString stringWithContentsOfFile:xmlPath usedEncoding:NSASCIIStringEncoding error:NULL];
xmlDisplay.text=fileContent;
}

replace
NSString *fileContent=[NSString stringWithContentsOfFile:xmlPath usedEncoding:NSASCIIStringEncoding error:NULL];
with
NSString *fileContent=[NSString stringWithContentsOfFile:xmlPath encoding:NSASCIIStringEncoding error:NULL];
you should not ignore the assing argument 2 of 'stringWithContentsOfFile:usedEncoding:error:' makes pointer from integer without a cast warning the compiler shows you.

i was facing same issue earlier . it is batter to save xml file inside document Directory itself not in any sub Folder .try to save in to Document Directory . hope should work....
or u can try
-(IBAction)xmlParse{
NSString *xmlPath=[[[[UIApplication sharedApplication]delegate] applicationDocumentDirectory]stringByAppendingPathComponent:#"xmlFile/toc.xml"];
NSError *error=nil;
NSString *fileContent=[NSString stringWithContentsOfFile:xmlPath usedEncoding:NSASCIIStringEncoding error:NULL];
if(nil!=fileContent)
xmlDisplay.text=fileContent;

Related

Initializing Nsdata with Nsdata as a string

I have some NSData output that I would like to convert to a string.
NSString * test = [NSString stringWithFormat:#"myfile.txt];
NSData *myData = [[NSData alloc] initWithContentsOfFile:(#"%#", test)];
This NSData was saved to a file, it looks like : 21fa9731 27c67c00 da1c3349 d82470eb 56f97b88 559f406c 6abecbb7 de020007 47a4541d 99c9c5e7 883f8bf1 165fba39
Do you know a way to get this string back as it was in "myfile.txt" ?
Thanks !
If data file somewhere on HDD (not in app bundle) you must provide full path to your data file.
NSString * test = [NSString stringWithFormat:#"myfile.txt];
NSData *myData = [[NSData alloc] initWithContentsOfFile:(#"%#", test)];
NSString* myString = [NSString alloc]initWithData:myData
encoding: NSUTF8StringEncoding];
Choose encoding in which you save you data file.
I don't know what your problem ist. You could share with us how the file was written so that we can get a bit closer.
However, you are doing much too complicated and therefore error prone. The following would to for reading a file with a constant name fo myfile.txt.
NSData *myData = [[NSData alloc] initWithContentsOfFile:#"myfile.txt"];
Frankly I don't even know in which directory myfile.txt is expected to be. And there are of course much better ways to deal with constant literals than using literals directly in the code.
BTW, what do you actually receive in myData? null?
(This is more of a comment than an answer, but the formatting is much better in answers.)

Retrieving a specific data

I am new to xcode.. and I would love to learn about retrieving data from XML.. This is a draft code that I have been stucked with for days.. I manage to display a list of XML codes
XML CODE:
<find>
<set_number>038881</set_number>
<no_records>000138874</no_records>
<no_entries>000007000</no_entries>
</find>
However, now I have some difficulties in retrieving only the set_number from this xml... The URL I have left it blank due to confidential purposes.. so dont mind about it.. The last two codes has resulted my app to force close.. Help!!
NSString *URL = [NSString stringWithFormat:#""];
NSMutableData *receivedData = [[[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:URL] ]autorelease];
NSString *theRecord = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
NSString *path = [theRecord valueForKey: #"set_number"];
NSLog(#"File Data: %#", path);
I tried to add in this code at the bottom instead..
if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?
I tried to add in this code at the bottom instead..
`if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}`
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?? Please help!!
To parse your XML use the NSXMLParser class.
NSString *path = [theRecord valueForKey: #"set_number"];
theRecord is a NSString instance that can not use valueForKey.
You should parse your xml string first and get the content you want from tag.
Or you should get substring in your string.

NSString WriteToFile not stay permanent?

I am trying to save text stored in an NSString variable in a text file that is stored with the main bundle of my project.
So far I have had no success and tried a lot of different methods.
Why doesn't this stay permanent?
NSString *pathToFile = [[NSString alloc]init];
pathToFile = [[NSBundle mainBundle] pathForResource:#"ListOfSavedImages" ofType:#"txt"];
NSLog(#"%#",pathToFile);
NSString *stringToWriteToFile = [[NSString alloc]init];
stringToWriteToFile=#"Adam";
NSLog(#"%#",stringToWriteToFile);
[stringToWriteToFile writeToFile:pathToFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"called!");
NSString *contentsOfFile1 = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#",contentsOfFile1);
The actual file doesn't change although the NSLog at the end of this code segment outputs "Adam" but I am also nslogging the contents of the file when the view loads and it always reverts back to the original text(it never actually changes). What am I doing wrong?
I am using Xcode 4.3, ARC, and storyboards.
As you are instantiating your variables locally, they will leak away when you hit the end of the block }.
Try using IVars declared as properties of the particular view controller, synthesized in the .m file.
Look at the C139p at Stanford Course on ITunes, preferably the earlier series given before ARC as this fully explains the concept of data persistence.

Weird problem with NSString initWithContentsOfFile

I have a .csv file in my bundle which I need to parse into an NSArray. The problem is when I init an NSString with contents of file (the file is located in my bundle), it returns nil. However, if I change the contents of the file, to anything else (random), it works. Is it possible there's some sort of string/character in the file that might be messing with the initialization?
It's just a simple csv file with 2 columns, a number, a comma, some text and "\n".
Thanks.
CSV => NSArray?
https://github.com/davedelong/CHCSVParser
*disclaimer: I wrote it.
Works for me:
NSStringEncoding usedEncoding = 0;
NSError *csvError = nil;
NSString *raw = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://pastebin.com/raw.php?i=RXPPwpvy"] usedEncoding:&usedEncoding error:&csvError];
NSLog(#"raw: %#", raw);
NSLog(#"%#", [NSArray arrayWithContentsOfCSVString:raw encoding:usedEncoding error:&csvError]);

Failure to write NSString to file on iPad

I'm using a text file to save the changes made by a user on a list (the reason that I'm doing this is so that I can upload the text file to a PC later on, and from there insert it into an Excel spreadsheet). I have 3 data structures: A NSMutableArray of keys, and a NSMutableDictionary who's key values are MSMutableArrays of NSStrings.
I iterate through these data structures and compile a file string that looks much like this:
(Key);(value)\t(value)\t(value):\n(Key);(value).. .so on.
SO, onto the actual question: When I attempt to save it, it fails. I'm 99% sure this is because of the file path that I'm using, but I wanted backup to check this out. Code follows:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [paths objectAtIndex:0];
NSString *fileString = [NSString stringWithString:[self toFileString]];
if(![fileString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL]){
NSLog(#"File save failed");
} else {
// do stuff
}
(Code above is re-copied, since the actual code is on a different computer. It compiles, so ignore spelling errors?)
I tried using NSError, but I got bogged down in documentation and figured I might as well ask SO while trying to figure out how to properly use NSError (might be a little bit of an idiot, sorry).
99% sure it's the NSArray *paths line that's tripping it up, but I don't know how else to get the documents directory.
Edit: Problem solved, and one final question: If I save it to the App's document directory, where can I go after I close the app to see if it saved properly? If it works like I think it does, isn't it sandboxed in with the app's installation on the simulator? (i.e. no way of checking it)
NSLog() that filePath string. I think you're trying to write to the directory itself, not to a file.
Try this instead:
filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"myfile.txt"];
What is the file name you want to save? The method
NSArray *paths = NSSearchPathForDirectoriesInDomains(...);
NSString *filePath = [paths objectAtIndex:0];
...
if(![fileString writeToFile:filePath ...
means you are saving the string into a file path which has the same name as a folder. This will of course fail. Please give it a name, e.g.
NSString* fileName = [filePath stringByAppendingPathComponent:#"file.txt"];
if(![fileString writeToFile:fileName ...
and try again.
BTW, to use NSError:
NSError* theError = nil;
if(![fileString writeToFile:fileName ... error:&theError]) {
// ^^^^^^^^^
NSLog(#"Failed with reason %#", theError);
// theError is autoreleased.
}