3

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

2 Answers 2

7

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

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

1
  • I struggled with the accepted answer because of ARC, but this solution worked like a charm. Thanks!
    – Jimmery
    Oct 25, 2012 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.