views:

630

answers:

2

Hello, 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

+1  A: 

You can call NSData's - (id)initWithContentsOfURL:(NSURL *)aURL routine. More info here:

http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData%5FClass/Reference/Reference.html

fbrereto
+4  A: 

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];
Ramin