Is it possible to read the raw HTML content of a web page that has been loaded into a UIWebView?
If not, is there another way to pull raw HTML content from a web page in the iPhone SDK (such as an equivalent of the .NET WebClient::openRead)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The second question is actually easier to answer. Look at the
stringWithContentsOfURL:encoding:error:method of NSString – it lets you pass in a URL as an instance of NSURL (which can easily be instantiated from NSString) and returns a string with the complete contents of the page at that URL. For example:After running this code,
googlePagewill contain the HTML for http://www.google.com, anderrorwill contain any errors encountered in the fetch. (You should check the contents oferrorafter the fetch.)Going the other way (from a UIWebView) is a bit trickier, but is basically the same concept. You’ll have to pull the request from the view, then do the fetch as before:
EDIT: Both these methods take a performance hit, however, since they do the request twice. You can get around this by grabbing the content from a currently-loaded UIWebView using its
stringByEvaluatingJavascriptFromString:method, as such:This will grab the current HTML contents of the view using the Document Object Model, parse the JavaScript, then give it to you as an NSString* of HTML.
Another way is to do your request programmatically first, then load the UIWebView from what you requested. Let’s say you take the second example above, where you have
NSString *pageas the result of a call tostringWithContentsOfURL:encoding:error:. You can then push that string into the web view usingloadHTMLString:baseURL:, assuming you also held on to the NSURL you requested:I’m not sure, however, if this will run JavaScript found in the page you load (the method name,
loadHTMLString, is somewhat ambiguous, and the docs don’t say much about it).For more info: