利用CMHTMLView实现webview基础功能,同时获取点击图片链接的功能

来源:互联网 发布:淘宝客成交家信誉吗 编辑:程序博客网 时间:2024/06/18 13:11

转载自:http://lipengxuan.easymorse.com/?p=552

mureev工程师编写了个实用的小工具,可以优化UIWebview的使用,最实用的地方是可以点击里面的img标签获取图片的src地址,这样可以做相应处理来很好的衔接html与iOS的交互,代码和例子在这个地址https://github.com/mureev/CMHTMLView 这里描述了简单的CMHTMLView使用方法,实现本地html页面的展示和点击图片获取src的效果。

首先将下载的项目里的CMHTMLView.h和CMHTMLView.m文件拷贝到自己的项目里,可以理解为这个类就要代替Webview了…

然后在需要添加网页的地方加上这段代码:

- (void)viewDidLoad

{

[super viewDidLoad];

CMHTMLView* htmlView = [[[CMHTMLView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height-100)] autorelease];

htmlView.backgroundColor = [UIColor whiteColor];

htmlView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

NSString* filePath = [[NSBundle mainBundle] pathForResource:@”detail” ofType:@”html”];  //引入html文件

NSData* htmlData = [NSData dataWithContentsOfFile:filePath];

NSString* htmlString = [[[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding] autorelease];

htmlView.alpha = 0;

//url的点击事件,获取url

htmlView.urlClick = ^(NSString* url) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”URL Click” message:url delegate:nil cancelButtonTitle:@”Close” otherButtonTitles:nil];

[alert show];

[alert release];

};

//图片的点击事件,获取src

htmlView.imageClick = ^(NSString* url) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Image Click” message:url delegate:nil cancelButtonTitle:@”Close” otherButtonTitles:nil];

[alert show];

[alert release];

};

[htmlView loadHtmlBody:htmlString competition:^(NSError *error) {

if (!error) {

[UIView animateWithDuration:0.2 animations:^{

htmlView.alpha = 1;

}];

}

}];

[self.view addSubview:htmlView];

}

 然后编译运行就可以了。
至于图片点击是怎么实现的呢?
这个类让html里面的img标签监听click事件,并把src传给window.location

        // Add onClcik js – window.location=”;

self.jsCode = [self.jsCode stringByAppendingFormat:@"document.getElementById('%@').addEventListener('click', function(event) {window.location='%@://imageclick?%@';}, false);", hash, kNativeShame, hash];

这么做的效果相当于打开一个web窗口链接就是src,但是在代理方法里面截取了这个地址,不打开新窗口,下面是代理方法:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

NSURL* url = [request URL];

if ([[url scheme] isEqualToString:kNativeShame]) {

if ([[url host] isEqualToString:@”imageclick”]) {

if (self.imageClick) {

self.imageClick([self.imgURLforHash objectForKey:[url query]]);

}

}

} else {

if ([[url absoluteString] isEqualToString:@”about:blank”]) {

return YES;

} else if ([[url host] isEqualToString:@”www.youtube.com”]) {

return YES;

} else if (navigationType == UIWebViewNavigationTypeLinkClicked) {

if (self.urlClick) {

self.urlClick([url absoluteString]);

}

} else if (navigationType == UIWebViewNavigationTypeOther) {

NSLog(@”Deny load url from UIWebView – %@”, [url absoluteString]);

return NO;

}

}

return NO;

}


原创粉丝点击