I just ran into this one and couldn't seem to get any clear answer from the documentation.
Im retrieving some XML through a HTTPS connection. I do all sorts of authentication etc. so I have a set of classes that deals with this in a nice threaded way.
The result is an NSString that goes something like:
<response>
//some XML formatted test
</response>
This means that there is no encoding="UTF-8" indent="yes" method="xml" or other header blocks to indicate that this is actual XML and not just an NSString.
I guess I will use [NSXMLParser initWithData:NSData] to construct the parser, but how will I format or cast my NSString of xml formatted text into a proper NSData object that NSXMLParser will understand and parse?
Hope it makes sense, thank you for any help given :)
You can convert a string to a NSData object using the dataUsingEncoding method:
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
You can then feed this to NSXMLParser.
The headers are optional, but you can insert the appropriate headers yourself if needed:
NSString *header = #"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
NSString *xml = [NSString stringWithFormat:#"%#\n%#", header, response);
NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *praser = [NSXMLParser initWithData:data];
By the time NSXMLParser has the data it's pretty much going to be expecting it to be XML ;-)
I'm pretty sure the processing instruction header is optional in this context. The way you get the NSString into the NSData is going to dictate the encoding (using dataUsingEncoding:).
(edit: I was looking for the encoding enum, but Philippe Leybaert beat me to it, but to repeat it here anyway, something like: [nsString dataUsingEncoding:NSUTF8StringEncoding])
I've passed NSStrings of XML in this way before with no issues.
Not specific to this question as such, but on the subject of XML parsing in an iPhone context in general you may find this blog entry of mine interesting, too.
Related
I have an object with the following members:
NSString *reqStr = "param1=val1¶m2=val2¶m3=val3&..";
NSData *imageData = [NSJPEGRepresentation (myimage)];
NSData *fileContents = [NSData initWithFileContents(myfile.txt)];
How can I send this out to Windows WCF? Do I send it as stream of bytes, and attach to httprequest? Or, will this be sockets? I am not sure how to pack these things as one thing as in one stream of bytes or whatever it may be the way to format such an object.
Any help?
Since you said that you already know how to send imageData which is NSData. Why not convert regStr to NSData and combine all three together as a single data and send.
To convert NSString to NSData:
NSData* strData=[regStr dataUsingEncoding:NSUTF8StringEncoding];
And use NSMutableData's appendData method to combine all three.
NSMutableData *combineData = [[NSMutableData alloc]initWithData:strData];
[combineData appendData:imageData];
[combineData appendData:fileData];
This S/O question might help:
File Upload to HTTP server in iphone programming
If the WCF endpoint is configured as HTTP then the same principles should apply regarding the multipart/formencoding of the image in question.
Edit:
Is this answer more helpful ?
HTTP "POST" request in iOS
I'd like to develop a very simple "bus timetable" app that loads a particular URL and can use the HTML to figure out bus numbers, their routes and expected times. Unfortunately it's a very simple website, so the data is spread across TD and DIV fields, rather than in xml.
Can anyone provide some pointers on where to start? I've had a look at NSURL, NSURLConnection and the like, and am able to download the contents of an HTML file, but I'm unsure what to do next.
Many thanks.
There are many ways to accomplish this task. Ultimately, you will want to retrieve something an easily-processed format other than raw html. Here is one way to do it:
I would recommend writing a server-side script that converts the html into an easily-digestible format, such as JSON.
If you have php experience, you write a script / web-service that grabs the needed elements and place the content in an associative array. Place the script on your server and have your application call the web-service URL when ready to retrieve the info.
Finally, return the information as a JSON object and parse the JSON into your app.
<?php
//parse html into the $array variable.
$array = json_encode($array);
echo $array;
?>
I would recommend using the SBJSON library for parsing the JSON object: Take a look at SBJSON
Initiate your NSURL request by calling the script URL.
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.yoursite/script.php"]];
If the request is successful, parse the resulting JSON: (assuming use of SBJSON library)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[[SBJSON alloc] init]autorelease];
NSDictionary *busData = [json objectWithString:responseString error: &error];
//busData contains bus data that you formatted...
Beware, this is assuming that you want to add your data to a dictionary and then display it appropriately. I consider this a mere snippet for formatting data in a way you desire. Parsing all of the html within the app may difficult and that is why I advocate formatting the data as JSON first. If you decide to go the XML route, there are several XML parsers as well.
I need to load data from a REST service, but the result is always (null) when I have any accentuation. I know this is an encoding problem but NSUrlConnection gives me no solution. The best result I got is to have all my text with strange codes in the place of the accentuated characters.
I already tried to use NSUrl like the following code and it works, but I need to set two headers for this connection.
NSURL *nsurl = [[NSURL alloc] initWithString:url];
NSString *data = [[NSString alloc] initWithContentsOfURL:nsurl encoding: NSUTF8StringEncoding error: nil];
Well I could have two solutions for this taks, adding headers do NSUrl connection or manage to make the encoding to work in NSURLConnection.
Does anyone have a solution?
You can add header fields for your request in an NSMutableURLRequest instance with setValue:forHTTPHeaderField:
Im working on simle RSS reader. This reader loads data from internet via this code:
NSXMLParser *rss = [[NSXMLParser alloc] initWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/user_timeline/50405236.rss"]];
My problem is with encoding. RSS 2.0 file is supposed to be UTF8 encoded according to encoding attribute in XML file.
<?xml version="1.0" encoding="utf-8"?>
So when I download URLs content I get text truncated after first occurance of char with diacritics, example: ľ š č ť ž ý á í é, etc.
I tried to solve the problem by downloading URL as UTF8 string, I used this code:
NSString *rssXmlString = [NSString stringWithContentsOfURL: [NSURL URLWithString: #"http://www.macblog.sk/rss.xml"] encoding:NSUTF8StringEncoding error: nil];
NSData *rssXmlData = [rssXmlString dataUsingEncoding: NSUTF8StringEncoding];
Did not help. Thanx for your responses.
Check out MWFeedParser on GitHub, it's an open source RSS/Atom feed parser I've released and it makes reading and parsing web feeds extremely easy.
There's a simple demo app too which shows how easy it is to implement.
Hope this might be of some use!
I'm working with the Google Docs API in my iPhone application. I've sent the proper POST request, and received a response along with some NSData. If I NSLog the NSData object, I get this:
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:theResponse error:NULL];
NSLog(#"%#",returnedData);
//output : <4572726f 723d4261 64417574 68656e74 69636174 696f6e0a>
I think the NSData is either an NSDictionary or an NSArray. I'm supposed to receive a couple of items back, an SID, an LSID, and an Auth.
If I could turn the NSData chunk into an NSDictionary I could just find the object for whichever key.
Can anyone help?
You will have to decode the data. Try the following:
NSString *result= [[NSString alloc] initWithData:returnedData encoding:NSASCIIStringEncoding];
Of course this will depend on how the data is encoded. NSUTF8StringEncoding might work instead.
You may just need to pass the data to an NSXMLParser
The best way to deal with web data is Doing NSXML parsing. No need of decoding data the parser will handle itself