Getting an XML file from URL to NSData object? - iphone

I need to load a .xml file from a URL adress into an NSData object for further parsing with some libraries that I already own, ( but they ask me the .xml file as NSData ), how could I do this ?
The url format would be something like this:
http://127.0.0.1/config.xml

Assuming it's UTF-8 data. If it's local (i.e. inside the bundle) something like:
NSError *error;
NSString* contents = [NSString stringWithContentsOfFile:PATHTOLOCALFILE
encoding:NSUTF8StringEncoding
error:&error];
NSData* xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
If it's on a remote site, something like this should do it. Note that it's synchronous. If you need asynchronous loading, then you'll have to make your own networking or use something like ASIHTTPConnection to download the file first.
NSError *error;
NSString* contents = [NSString stringWithContentsOfUrl:[NSURL URLWithString:URLOFXMLFILE]
encoding:NSUTF8StringEncoding
error:&error];
NSData* xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];

You can call NSData's - (id)initWithContentsOfURL:(NSURL *)aURL routine. More info here:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html

Related

CHCSVParser - how to load from webserver

I would like to parse csv from webserver which gets updated everyday.I am using the csvparser from this link https://github.com/davedelong/CHCSVParser and I am using this code:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL] encoding:NSUTF8StringEncoding error:&err];
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVString:lunchFile usedEncoding:&encoding error:nil];
I get this error :
No visible #interface for 'CHCSVParser' declares the selector 'initWithContentsOfCSVString:usedEncoding:error:'
I checked this link Load remote csv into CHCSVParser and its not working .I am a noob to ios ,Please let me know how to fix this .Really Appreciate the help.Thanks in Advance.
It should probably be:
NSError *err;
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL]
encoding:NSUTF8StringEncoding
error:&err];
// if you're going to create a CHCSVParser yourself, the syntax is:
CHCSVParser *p = [[CHCSVParser alloc] initWithCSVString:lunchFile
encoding:NSUTF8StringEncoding
error:&err];
// or, if you're going to use NSArray+CHCSVAdditions.h, the syntax might be:
NSArray *array = [[NSArray alloc] initWithContentsOfCSVString:lunchFile
encoding:NSUTF8StringEncoding
error:&err];
Note:
You don't need to alloc/init the NSError object; these classes that take a NSError ** parameter will create the autorelease error object for you if they encounter an error; otherwise they leave it alone;
The CHCSVParser class method is not initWithContentsOfCSVString, but rather initWithCSVString;
Alternatively, if you use the NSArray class extension, then the syntax is arrayWithContentsOfCSVString or initWithContentsOfCSVString; and
You specified an encoding of &encoding, but this parameter is not a pointer, so I don't see how that can possibly be right; I've just specified the encoding.
I assume you want to use the NSArray+CHCSVAdditions category method initWithContentsOfCSVString or arrayWithContentsOfCSVString (which gives you an autorelease object), not the CHCSVParser, but it's up to you.

Store and Load File from URL

iPhone App
I am currently trying to understand how i can store a file from a URL to the documents directory and then read the file from the documents directory..
NSURL *url = [NSURL URLWithString:#"http://some.website.com/file"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:#"Timetable.ics"];
[data writeToFile:storePath atomically:TRUE];
I got this code from http://swatiardeshna.blogspot.com/2010/06/how-to-save-file-to-iphone-documents.html
I want to know if this is the correct way to do this and i want to know how i can load the file from the documents directory into an NSString..
Any help will be greatly appreciated.
What you have looks correct, to read that file back into a string use:
EDIT: (changed usedEncoding to encoding)
NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:storePath encoding:NSUTF8StringEncoding error:&error];
Of course you should change the string encoding type if you are using a specific encoding type, but UTF8 is likely correct.
If you're doing this on your main thread, then no it's not correct. Any sort of network connection should be done in the background so you don't lock up the interface. For that, you can create a new thread (NSThread, performSelectorInBackground:, NSOperation+NSOperationQueue) or schedule it on the run loop (NSURLConnection).

convert .zip file into NSData

Hey, Is it correct to initialize an NSData with a zip file? I want to convert a zip file into NSData and construct another file with the data (in simple language 'copy it'). I have the code as:
NSURL *theFileUrl = [NSURL URLWithString: #"file://localhost/Users/xxx/Desktop/testZippedFile.zip"];
NSData *data = [NSData dataWithContentsOfURL: theFileUrl];
When I, NSLog(#"Data: %#", data) , i do get some output but when I try to initialize an NSString with this data, it doesn't work:
NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
`NSLog(#"String: %#", string)`
I get the log as: String: PK
Can anyone point out my mistakes please.
Thanks in advance!
Why do it that way? NSFileManager will do it for you :)
[[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:nil];
However, this only works for files that are local - if you want to copy a file from a server, you should have a look at NSURLConnection to load the data and then NSData's writeToFile:atomically: method to save the contents to the file system (found here.)
PK is the output you should expect.
The first 2 Characters in every zip-file are PK. Then there are some unprintable chars and at some point after those there is a character with a value of 0
If you create an NSString out of NSData all values up to the first 0-value are taken into account.
NEVER convert binary data into NSString.

to print local xml file through NSData?

i want to take some xml data from local path,and to parse,but when i use following code
NSLog returns(content) different texts which is differed from xml file, how can i get exact xml data to check ,it consists correct xml data or not? any help please? when i parse , it returns nothing..i have saved the file as .xml and copied to local resource folder?
NSString *xmlFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"samp.xml"];
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath];
NSData *data = [NSData dataWithBytes:[xmlFileContents UTF8String] length:[xmlFileContents lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
NSString *content=[[NSString alloc]
initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
NSLog(#"%#",content);
This is almost assuredly an encoding problem. Make sure your xml file is in UTF8 or convert it to UTF8 before you try to create the NSData object. Once that's done, the following code produces the same output as input.
NSString *open = [NSString stringWithContentsOfFile: [#"~/Desktop/note" stringByExpandingTildeInPath] encoding: NSUTF8StringEncoding error: NULL];
NSData *data = [NSData dataWithBytes: [open UTF8String] length: [open lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
NSString *save = [NSString stringWithUTF8String: [data bytes]];
[save writeToFile: [#"~/Desktop/note2" stringByExpandingTildeInPath] atomically: NO encoding: NSUTF8StringEncoding error: NULL];
You'll probably want to use one of the NSXML classes, unless you want to do all of the parsing yourself.

How to get the contents of a text file (stored locally in the documents directory) into an NSString?

How to retrieve the contents of a TEXT FILE stored locally in the documents directory?
Assuming the text is UTF-8 encoded:
NSData *textFileData = [NSData dataWithContentsOfFile:pathToTextFile];
NSString *textFileString = [NSString stringWithUTF8String:[textFileData bytes]];
You can also use this NSString class method (assuming the text is UTF-8):
NSString *content = [NSString stringWithContentsOfFile:pathToTextFile encoding:NSUTF8StringEncoding error:&error];
error should be a pointer to an NSError object.