iphone: Getting xml with UIWebView? - iphone

I have the following url http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured?&start-index=1&max-results=15&v=2
I am trying to load it in UIWebView and then use javascript to get its contents, and parse it with NSXMLParser.
My code looks like that:
-(void)startDownloading{
NSString *urlStr = [NSString stringWithFormat:#"http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured?&start-index=%d&max-results=%d&v=2", range.location, range.length];
NSLog(urlStr);
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[browser loadRequest:request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.firstChild.innerHTML"];
NSLog(theStr);
NSData *receivedData = [theStr dataUsingEncoding:NSUTF8StringEncoding];
}
the problem is that the data that I receive can't be parsed with NSXMLParser. The text looks like that:
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:etag='W/"DUADR347eCp7ImA9Wx5UFkg."'><id>tag:youtube.com,2008:standardfeed:us:recently_featured</id><updated>...
while if I had used just the regular approach of getting data (without browser) I would get:
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:etag='W/"DUADR347eCp7ImA9Wx5UFkg."'><id>tag:youtube.com,
Why are the characters changing? And how can I prevent it
BTW to those who are wondering why I'm even bothering to do this - I think that this method gets the data quicker.

The data is being escaped, you need to unescape it. Take a look at:
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
"BTW to those who are wondering why I'm even bothering to do this - I think that this method gets the data quicker."
Don't prematurely optimize.

Related

Extract XML from UIWebView

I'm trying to extract some XML from a UIWebView, and not having much luck. This is what the entire document looks like:
<?xml version="1.0" encoding="utf-8"?>
<authResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<firstName>Name here</firstName>
<lastName>Name here</lastName>
<membershipTier>Membership level</membershipTier>
<errorMessage />
<isValid>1</isValid>
</authResponse>
I have tried a number of variations of the stringByEvaluatingJavaScriptFromString method, but this is the only one that will return anything for me:
[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.textContent"]
However, I need the raw XML, not the text content. Any suggestions?
EDIT: I have control over the XML, so it can be modified if need be.\
EDIT 2: As requested, code I am using to load the request is below. Note that this request is for a login screen. Once the user has entered their credentials, the page after that is the one I am trying to extract the results from. I determine which is the current page in webViewDidFinishLoad by testing the current mainDocumentURL for the UIWebView object.
NSString* urlString = kLoginURL;
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
UIWebView* tmpWebView = [[UIWebView alloc] init];
self.webView = tmpWebView;
[tmpWebView release];
self.webView.delegate = self;
[self.webView loadRequest:request];
Just wrote a little test program to figure this out (fun!). It loads the UIWebView contents via:
NSString * data = #"<?xml version=\"1.0\" encoding=\"utf-8\"?><authResponse xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><firstName>Name here</firstName><lastName>Name here</lastName><membershipTier>Membership level</membershipTier><errorMessage /><isValid>1</isValid></authResponse>";
[self.webview loadHTMLString: data baseURL: nil];
I then passed the string document.getElementsByTagName('body')[0].innerHTML to stringByEvaluatingJavaScriptFromString
and it returns what you want:
<authresponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><firstname>Name here</firstname><lastname>Name here</lastname><membershiptier>Membership level</membershiptier><errormessage><isvalid>1</isvalid></errormessage></authresponse>
i'd grab the whole html as a string on a seperate thread, or use this as the basis to load the webview:
NSString *xmlString = [NSString stringWithContentsOfURL:yourURL]
You can try using kissxml to retrieve the whole xml structure.
Or you can just save the response into a string from your NSURLRequest or if you are using other libraries to do a http connection
NSURL *url = [[NSURL alloc] initWithString:#"http://www.w3schools.com/xml/note.xml"];
NSString *myString = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:(NSURL*)url] encoding:NSISOLatin1StringEncoding];
The code above is a sample on how you can retrieve the xml structure. This is much easier than using uiwebview. The sample xml encoding is using ISO-8859-1 so you have to set the correct encoding so that the data will be readable
I would suggest going with Nik's suggestion - get the request URL and get its content in an NSString.
OR you can send a request to the login URL (you are already intercepting the requests being sent) and get a response in a string.
If you want to read the entire body tag's content or the html and body tag's content, you might just do this
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
or
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:#"document.all[0].innerHTML"];
You can use either of these as per your need:
NSString *html1 = [webView stringByEvaluatingJavaScriptFromString:
#"document.body.innerHTML"];
NSString *html2 = [webView stringByEvaluatingJavaScriptFromString:
#"document.documentElement.outerHTML"];

Parse an XML stored in NSData with libxml2

please can you help me using libxml2 to parse an XML stored in a NSMutableData object? I get the XML using
NSString *path = "http://www.mySite.com/XMLPATH.xml";
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
and
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data_
{
[data appendData:data_];
}
where data is an instance of NSMutableData.
Now how can i start the libxml2 to parse this data? I need the equivalent of
NSString *xml; // string containing XML
mlDocPtr doc = xmlParseMemory([xml UTF8String], [xml lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
where xml is my NSMutabledata and not a NSString.
Thanks!
EDIT:
I'm currently using NSXMLParser to do the job, but i'd like to have a parser that automatically parses all the XML, with its node structure. With NSXMLParser i need to manually set the node structure of my XML
Any reason you are not using the NSXMLParser. It is a nice wrapper written by Apple and included on all iOS versions.
http://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html

How do I make initWithContentsOfURL wait for an xml page that is generated dynamically?

I am trying to send a query as part a the URL to obtain an XML file, and then trying to parse the XML file using NSXMLParser and initWithContentsOfURL. However the parser is not able to parse the file. I tested the parser with the same file, but this time the file was saved on the server (it was not being generated) and it worked just fine, so I know it is not a problem with the parser.
I have come to think that it does not parse it because I need to load the file before I try to parse it, or give the initWithContentsOfURL time to load the contents. So I tried to put those contents in a NSString and a NSData and using a sleep function as well as using a block but that did not work either.
What would be the best way to go about this problem?
Here is some of the code:
NSString *surl = [NSString stringWithFormat:#"http://lxsrv7.oru.edu/~maria_hernandez/query.xml"];
url = [NSURL URLWithString:surl];
NSString *curl = [[NSString alloc] initWithContentsOfURL:url];
NSLog(#"URL: %#", surl);
NSLog(#"URL Content: %#", curl);
SXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:receivedData];
//Other stuff we have tried:
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:surl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLResponse = nil;
NSError = nil;
receivedData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &theResponse error: &error];
Let me know if you have more questions or if you wish to see more code.
Thanks!
have you tried setting a delegate for the NSXMLParse that implements the NSXMLParserDelegate which has events for parsing the document
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html

UIWebView doesn't load some link

hello
I'm trying to write an rss feed viewer for my iPhone. In my DetailView I have a UIWebView where I want to display specific link retrieved with the rss item.:
NSString* url = [data objectForKey:#"link"];
NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
NSLog(#"Selected link:%#",url);
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:encodedUrl]];
[itemWebpage loadRequest:request];
[request release];
now,if the retrieved link is something like
www.shazaam.com
it works. But as soon as the link is something like:
http://www.shazam.com/music/web/track?id=41970148"
it doesn't. I suppose it's because of the parameter...but how can I fix the problem????
thanks a lot!
elos
stringByAddingPercentEscapesUsingEncoding: is for when you want to put a string into a query variable. You don't need to do it for entire URLs. The question mark is being encoded when it shouldn't be, so you are getting a 404. Don't encode the URL and you should be fine.

UIWebView: Error while loading URL

I am trying to build an RSS reader for the Tom's Hardware website.
I have an error when I try to load an URL into an UIWebview from an RSS link.
Here'is my code:
- (void)viewDidLoad {
[super viewDidLoad];
if (self.url != nil) {
NSURL *requestUrl = [NSURL URLWithString:self.url];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:requestUrl];
[webView loadRequest:requestObj];
}
}
The url is setted by the parent controller.
When the URL comes directly from the RSS, I have an error in log:
[2234:207] Error Domain=WebKitErrorDomain Code=101 UserInfo=0x3a6a240 "Operation could not be completed. (WebKitErrorDomain error 101.)"
When I set manually the URL with the same URL like below, it work !
self.url = #"http://www.presence-pc.com/tests/fraude-financiere-paget-macafee-23198/#xtor=RSS-12";
Here is an URL exemple: http://www.presence-pc.com/tests/fraude-financiere-paget-macafee-23198/#xtor=RSS-12. I have no idea about that problem.
I hope you can help me.
Best regards.
Thanks guy, that'it, I have split the URL like this:
NSArray *split = [url componentsSeparatedByString:#"#"];
NSURL *requestUrl = [NSURL URLWithString:[[split objectAtIndex:0] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
and now it work , thanks for your help !
I have this code which also triggers error code 101
_request = [NSURLRequest requestWithURL:[NSURL URLWithString:redirectUrl]];
[editorWebView loadRequest:_request];
RedirectURL is an NSString which has this format http%3A%2F%2Fwww.linkedin.com%2Fnhome%2F
I tried removing percent escapes using the method of NSString and it now works.
[redirectUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I think the problem can be the anchor in your URL, a friend got the same problem