iphone's nsxmlparser parsing RSS causes encoding problems - iphone

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!

Related

NSUrlRequest itself adding %0 in url

The NSURLRequest is adding %0 in request. I created the string and converted it into base 64 then send to url, but NSURLRequest is automatically adding %0 in it. Below is the code i am using.
This is how converted to base 64.
NSData *plainTextData = [totalStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
NSLog(#"encoded url:%#",base64String);
When Api called.
NSString *urlStr = [NSString stringWithFormat:#"http://mabct.co/api/checkin/%#", [code valueForKey:#"code"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:urlStr]];
// [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSString *responseString = [MyEventApi sendRequest:request];
NSError *error;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"dict in API-------------%#",results);
return results;
This is the converted string in to base 64
eyJldmVudElkIjoiNDAiLCJzZWF0IjoiMTBfS2FyYW4gU3VraGlqYV8yNC0wNC0yMDEzIDE3OjE3IiwidXNlcklkIjoiMTAifQ==
This is what NSURLRequest is sending.
eyJldmVudElkIjoiNDAiLCJzZWF0IjoiMTBfS2FyYW4gU3VraGlqYV8yNC0wNC0y%0D%0AMDEzIDE3OjE3IiwidXNlcklkIjoiMTAifQ==
This is what i am sending in encoding
"{"eventId":"47","seat":"10_Karan Makhija_24-04-2013 10:06","userId":"10"}"
I am not getting what is wrong, please guide for the above.
Thanks in advance.
I see that %0D%0A is being added to your original string. I googled it and found that:
%0D%0A is the encoded ASCII non-printable characters of ,
which on Microsoft platforms is a NewLine So:
Consider if you accidentally could have replaced some HTML by hitting the return key while editing your files.
2a. Be aware of what
encoding your editor uses for saving the files (typically either
ASCII, ANSI, or Unicode)
2b. Your webserver (an IIS6, likely running
on a Windows 2003 Server) serves the files as UTF-8 encoded, which is
fine - But you may want to verify that it actually reads the files
using same encoding as you've used for saving the files.
Here, is the SOURCE if you want to check.
EDIT
Make sure that your webserver and client uses the same encoding (i.e. NSUTF8StringEncoding or any other, but same)
Also, IF base 64 encoding is there on web server. Follow this link, for implementing category for such encoding/decoding. I hope this will help you.

objective c string encoding issue

My app receives some data from server which is in XML format and some tags contains Japanese words. When I tried to execute the link in the browser, it gets the correct response in Japanese. For example:
<root>
<categorylist>
<cid>19</cid>
<cname>ファミリー</cname>
<lang>jap</lang>
</categorylist>
</root>
..but in my app, the response string is in some encoded format like the following:
<root>
<categorylist>
<cid>19</cid>
<cname>ファミリー</cname>
<lang>jap</lang>
</categorylist>
</root>
My code to receive XML from the server is:
NSString *req=#"http://www.myserver.com/category.php?lang=jap";
NSString *resultString=[NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:nil];
Is there a problem with my code? How can I convert the response to correct Japanese strings?
Try looking at some of the decoding methods listed on this question: HTML character decoding in Objective-C / Cocoa Touch

Objective-C: Parsing a non-xml website

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.

NSXMLParser Doesn't Parse when URL contains chars from different language

hi there I am working on a program that sends requests via XML Webservice and parses the data using NSXML parser.
I've used that method for anything on my program and it works flawlessly until I had this:
NSXML Parser returns data and parses when the URL is like that:
http://someasp.netserver/xmlservices/service1.asmx/getSales?date1=01.03.2011%2000:00:00&date2=%2023.03.2011%2000:00:00%20&Name=JOHN
but when I change the URL to this:
http://someasp.netserver/xmlservices/service1.asmx/getSales?date1=01.03.2011%2000:00:00&date2=%2023.03.2011%2000:00:00%20&Name=JÜRGEN
it doesn't return anything.
I copy and paste those URL addresses into a web browser and I can see the XML results but on the iPhone NSXMLparser just ignores the parsing and returns nothing.
I have a list of 15 "Name" values in my program, and whenever the name contains characters like 'ö,ü,ş,İ,ç' it just returns zero, otherwise it's working normally.
Thanks for helping.
Also, here's my parsing code in the program :
NSURL *URL=[[NSURL alloc] initWithString:testURL]; //test url is the request string
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL :URL];
[parser setDelegate:self];
[parser parse];
You need to perform URL encoding, you can't just shove special characters into a URL as-is.
Please see this question:
iPhone URL encoding Problem
Or search for "iphone url encoding".

NSXMLParser init with XML in NSString format

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.