Getting an XML file from URL to NSData object?
Solution 1
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];
Solution 2
You can call NSData
's - (id)initWithContentsOfURL:(NSURL *)aURL
routine. More info here:
Goles
Software Craftsman. Extremely interested in Web Technologies and Mobile Game Development. Using the sweet Obj-C, the evil C++ and the elegant Lua. Have been using lot's of Ruby spices in the mix lately.
Updated on June 04, 2022Comments
-
Goles almost 2 years
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: