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"];
Related
I have a header string, footer string and body of the HTML page. I need to programmatically include some text in the body and then I need to input all this data in a UIWebView to load the page. I need to input the final HTML string into a UIWebView controler, so that it will launch the page I designed. Could someone please share your ideas how can I achieve this?
Thanks!
You mean something like:
NSString *html = [NSString stringWithFormat: #"<html><head><style>body{background-color:black}</style></head><body>the body goes here</body>"];
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0,76.0,320.0,404.0)];
[myWebView loadHTMLString:html baseURL:nil];
If you, for example, have head stored in headString and body in bodyString you could combine them with:
[NSString stringWithFormat: #"<html>%#%#</html>", headString, bodyString];
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
i have web site that show a text and i update this text every day , i want to show this text on iphone application , how can i get this text from web site from application ?
what should i do ?
thanks
1-> you require to connect with your web server thought HTTP connection.
2-> Make the request to server.
3-> Parse server response that may contain your "Text".
For technical assistance Read below.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
I don't recommend this as the best way to obtain a string from your own web server.
This should point you in the right direction, don't expect it to compile cleanly.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:#"http://example.com/whatever"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:#"<h1>" intoString:NULL];
[scanner scanUpToString:#"</h1>" intoString:&token];
This will capture text from first h1 tag.
The simplest way is to create a REST API. That might sound tough but it's really easy. On the server side, create a new page which holds only the raw text. Usually it's best to keep it there in JSON/XML format, but a simple text will also work. Now from the iPhone, just contact that address and the response data will contain the text. Parsing an existing page is not something I recommend, because changing that page in the future might result in the app not working anymore.
This is a answer quite late but I think it still might help in your future. You can go into parsing the website and that is the right way to do it but I will show you how to do it a different way, this can also be used to read xml, html, .com, anything and also, .rss so it can read RSS Feeds.
Here :
This can get your first paragraph, if you request I will show you how to get the second paragraph and so on.
//This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
{
NSString *webString2222 = mastaString;
NSScanner *stringScanner2222 = [NSScanner scannerWithString:webString2222];
NSString *content2222 = [[NSString alloc] init];
//Change <p> to suit your need like <description> or <h1>
[stringScanner2222 scanUpToString:#"<p>" intoString:Nil];
[stringScanner2222 scanUpToString:#"." intoString:&content2222];
NSString *filteredTitle = [content2222 stringByReplacingOccurrencesOfString:#"<p>" withString:#""];
description.text = filteredTitle;
}
Title ? Same deal change the <p> to a <title> in RSS <description> and <title>.
Image ? Same deal change the <p> to what ever your RSS or website uses to get a image to find
But remember for both of them when you change the` you see the link which says stringByReplacingOccurences of you have to change that as well.
out then you have to delete this and make your code like this :
/This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
NLog(#"%#", string)
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
Now check your log it shows your whole website html or rss code then you scroll and read it and find your image link and check the code before it and change the String Scanner to your needs which is quite awesome and you have to change the stringByReplacingOccurences of.
Like I said images are a bit tricky when you do it with this method but XML Parsing is a lot easier ONCE you learn it , lol. If you request I will show you how to do it.
Make sure :
If you want me to show you how to do it in XML just comment.
If you want me to show you how to find the second paragraph or image or title or something just comment.
IF YOU NEED ANYTHING JUST COMMENT.
Bye have fun with code I provided, anything wrong JUST COMMENT! !!!!
:D
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.
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.