Krutarth Patel
Krutarth Patel

Reputation: 3455

How to load two urls in webview Together in iOS?

i am loading url in webview. i have two types of data to display

1)text(html string)

2)url

here is my code

To display text

[self.webView loadHTMLString:[self.arr objectAtIndex:indexPath.row][@"text"] baseURL:nil];

To display url

NSString *str = [NSString stringWithFormat:@"%@%@",URL,strpdf];
        NSURL *websiteUrl = [NSURL URLWithString:str];
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
        [self.webView loadRequest:urlRequest];

issue is when i loading both data,data is overwrite. i want to display both data in webview but right now only text or image is displaying.

what is solution for this.

Upvotes: 1

Views: 829

Answers (1)

aircraft
aircraft

Reputation: 26886

My demo is below:

enter image description here

#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>

@property(nonatomic, strong) UIWebView *webView;

@property (nonatomic, copy) NSString *html_str;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI ];
}

- (void)initUI {

    _html_str = @"I love google...";  // the html text you want

    CGRect frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    _webView = [[UIWebView alloc] initWithFrame:frame];
    _webView.delegate = self;

    NSString *str = [NSString stringWithFormat:@"http://chsezhsan195030.e-fae.cn/"];
    NSURL *websiteUrl = [NSURL URLWithString:str];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
    [self.webView loadRequest:urlRequest];

    [self.view addSubview:self.webView];


}

#pragma mark - webview delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView {


     NSString *script_str = [NSString stringWithFormat:@"var body = document.getElementsByTagName('body')[0];\
     var script = document.createElement('div');\
     script.innerText = '12345678'%@;\
     script.style.width = window.innerWidth + 'px';\
     script.style.height = '300px';\
     script.style.backgroundColor = '#eeeeee';\
     body.appendChild(script); \
     body.insertBefore(script, body.childNodes[0]);",_html_str];

    NSString *function = [NSString stringWithFormat: @"var script = document.createElement('script');\
    script.type = 'text/javascript';\
    script.text = \'function myFunction() { \
 %@ };'\
    document.getElementsByTagName('head')[0].appendChild(script);", script_str];

    [self.webView stringByEvaluatingJavaScriptFromString:function];

    [self.webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];

}

@end

But you should attention most of the url is prevented for inject js code,especially the https url, so you can not insert the html text above the google's index page.

Upvotes: 1

Related Questions