objectiveccoder001
objectiveccoder001

Reputation: 3031

getting HTML source code from webView

I'm making an iphone app...can I get the source from it in objective-c?

Thanks! Elijah

Upvotes: 1

Views: 2424

Answers (2)

Adam Milligan
Adam Milligan

Reputation: 2826

You can get anything from the web view that JavaScript can return using stringByEvaluatingJavaScriptFromString:. Try something along the lines of

document.lastChild.outerHTML

The document will likely have two child nodes; the first will be the DOCTYPE, and the second the <html> element.

Upvotes: 1

Travis
Travis

Reputation: 5061

If you need to get the contents of the current URL in your web view you could have something like this in a UIViewController. I didn't compile this code, so there may be some syntax errors, but this should be a solid starting point for your problem.

@interface aViewController : UIViewController <UIWebViewDelegate>
    UIWebView *webView;
    NSString *htmlSource;
@end
@implementation aViewController 

-(void) viewDidLoad {
    CGRect webFrame = [[UIScreen mainScreen] applicationFrame];

    self.webView = [[UIWebView alloc] initWithFrame:webFrame];
    self.webView.delegate = self;

    NSURL *aURL = [NSURL URLWithString:@"http://www.myurl.com"];
    NSURLRequest *aRequest = [NSURLRequest requestWithURL:aURL];
    //load the index.html file into the web view.
    [self.webView loadRequest:aRequest];
}    
//This is a delegate method that is sent after a web view finishes loading content.
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"finished loading");
    self.htmlSource = [[NSString alloc] initWithData:[[webView request] HTTPBody] encoding:NSASCIIStringEncoding];
}

@end

Upvotes: 0

Related Questions