WebView加载HTML时替换图片地址

这两天做项目时,因为实际情况,需要将获取到的html字符串加载出来,并将所有img标签的地址加上主机

开始的时候,我使用系统自带的方法

1 NSURL *baseURL = [NSURL URLWithString:@"主机"];
2 [webView loadHTMLString:htmlStr baseURL:baseURL];

baseURL会在加载图片的时候自动加到图片地址的前面,但是这样写有个问题,就是主机为http://www.baidu.com的话,这样做没问题,若主机为http://www.baidu.com/sss的话,图片就加载不出来,我没找到原因所在(若你知道的话,可以告诉我)

然后,我就尝试使用js的方法解决

- (void)webViewDidFinishLoad:(UIWebView *)web
{
    int count = [[webView stringByEvaluatingJavaScriptFromString:@"document.images.length"] intValue]; //获取img标签的数量
    for (int i=0; i<count; i++) {
        NSString *old = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.images[%d].src", i]]; //获取图片地址
        old = [old stringByReplacingOccurrencesOfString:@"file://" withString:@""]; //若上面baseURL为空,则将图片自动添加的主机去掉
        NSString *new = [NSString stringWithFormat:@"document.images[%d].src='%@'", i, [NSString stringWithFormat:@"%@%@", Test_Host, old]]; //将主机和图片地址拼接在一起
        [webView stringByEvaluatingJavaScriptFromString:new]; //更新图片
    }
}

 

posted on 2015-07-31 10:56  rgshio  阅读(1106)  评论(0编辑  收藏  举报

导航