iOS UI基础-15.0 UIWebView
WebView介绍
知识点:
- 代码创建一个UIWebView
- OC调用html的js
- js页面调用OC
相关代码实现
代码创建一个UIWebView
// 1.webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
webView.delegate = self;
// 伸缩页面至填充整个webView
webView.scalesPageToFit = YES;
// 隐藏scrollView
webView.scrollView.hidden = YES;
[self.view addSubview:webView]; // 2.加载网页
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.dianping.com/tuan/deal/5501525"]];
[webView loadRequest:request];
OC调用html的js
关键代码:
// 删除底部的链接的JS
[js1 appendString:@"var footer = document.getElementsByTagName('footer')[0];"];
[js1 appendString:@"footer.parentNode.removeChild(footer);"];
// OC中调用js
[webView stringByEvaluatingJavaScriptFromString:js1];
完整示例
创建一个webView,实现UIWebViewDelegate代理,在页面加载完毕后,通过js删除相关的html代码。
#import "HMViewController.h" @interface HMViewController () <UIWebViewDelegate>
@property (nonatomic, weak) UIActivityIndicatorView *loadingView;
@end @implementation HMViewController /**
test.html存在于服务器,里面的html和js代码,我们是无法修改的
如果test.html显示在手机端,把那个ul去掉
*/ - (void)viewDidLoad
{
[super viewDidLoad];
// 1.webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
webView.delegate = self;
// 伸缩页面至填充整个webView
webView.scalesPageToFit = YES;
// 隐藏scrollView
webView.scrollView.hidden = YES;
[self.view addSubview:webView]; // 2.加载网页
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.dianping.com/tuan/deal/5501525"]];
[webView loadRequest:request]; // 3.创建一个加载蒙板
UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[loadingView startAnimating];
loadingView.center = CGPointMake(, );
[self.view addSubview:loadingView];
self.loadingView = loadingView;
} // OC -> JS
// 在OC中调用JS #pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 执行JS代码,将大众点评网页里面的多余的节点删掉
NSMutableString *js1 = [NSMutableString string];
// 0.删除顶部的导航条
[js1 appendString:@"var header = document.getElementsByTagName('header')[0];"];
[js1 appendString:@"header.parentNode.removeChild(header);"]; // 1.删除底部的链接
[js1 appendString:@"var footer = document.getElementsByTagName('footer')[0];"];
[js1 appendString:@"footer.parentNode.removeChild(footer);"];
// OC中调用js
[webView stringByEvaluatingJavaScriptFromString:js1]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSMutableString *js2 = [NSMutableString string];
// 2.删除浮动的广告
[js2 appendString:@"var list = document.body.childNodes;"];
[js2 appendString:@"var len = list.length;"];
[js2 appendString:@"var banner = list[len - 1];"];
[js2 appendString:@"banner.parentNode.removeChild(banner);"];
[webView stringByEvaluatingJavaScriptFromString:js2]; // 显示scrollView
webView.scrollView.hidden = NO; // 删除圈圈
[self.loadingView removeFromSuperview];
});
} @end
js页面调用OC
oc加载的页面中,url链接跳转及请求,都会被shouldStartLoadWithRequest这个代理方法拦截,因而,我们在这里做处理。
html页面和oc两方都协商好,使用一个头文件来定义一个url链接请求,如:
// 调用OC中call方法
window.location.href = 'hm://call';
hm:// 就是相应的头文件了。接着,通过截取字符串的方式,来判断头文件是“hm://”开头的就是请求oc代码
具体代码实现。
test.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body>
<div>
<button onclick="fn_open_camera();">拍照</button>
</div>
<div>
<button onclick="fn_call();">打电话</button>
</div>
<a href="http://www.baidu.com">百度</a>
<script>
function fn_call() {
// 调用OC中call方法
window.location.href = 'hm://call';
} function fn_open_camera() {
// 调用OC中openCamera方法
window.location.href = 'hm://openCamera';
}
</script>
</body>
</html>
oc相关代码
#import "HMViewController.h" @interface HMViewController () <UIWebViewDelegate>
@end @implementation HMViewController - (void)viewDidLoad
{
[super viewDidLoad];
// 1.webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
webView.delegate = self;
[self.view addSubview:webView]; // 2.加载网页
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
} #pragma mark - UIWebViewDelegate
/**
* webView每当发送一个请求之前,都会先调用这个方法(能拦截所有请求)
*/
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = request.URL.absoluteString;
NSRange range = [url rangeOfString:@"hm://"];
NSUInteger loc = range.location;
if (loc != NSNotFound) { // url的协议头是hm
// 方法名
NSString *method = [url substringFromIndex:loc + range.length]; // 转成SEL
SEL sel = NSSelectorFromString(method);
[self performSelector:sel withObject:nil];
}
return YES;
} /**
* 打电话
*/
- (void)call
{
NSLog(@"call----");
} /**
* 打开照相机
*/
- (void)openCamera
{
NSLog(@"openCamera----");
} @end
上面这样就实现了,点击拍照和打开照相机,都会调用oc代码,而点击百度,则跳到百度的页面。
网易新闻详情
#import "HMViewController.h" @interface HMViewController () @end @implementation HMViewController - (void)viewDidLoad
{
[super viewDidLoad]; // 1.url
// http://c.m.163.com/nc/article/A7A94MCL00963VRO/full.html
NSURL *url = [NSURL URLWithString:@"http://c.m.163.com/nc/article/A7AQOT560001124J/full.html"]; // 2.requets
NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSDictionary *news = dict[@"A7AQOT560001124J"];
[self showNews:news];
}];
} - (void)showNews:(NSDictionary *)news
{
// 1.取出网页内容
NSString *body = news[@"body"]; // 2.取出图片
NSDictionary *img = [news[@"img"] lastObject];
NSString *imgHTML = [NSString stringWithFormat:@"<img src=\"%@\" width=\"300\" height=\"171\">", img[@"src"]]; // 2.创建一个webView,显示网页
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
[self.view addSubview:webView]; // 3.拼接网页内容
NSString *html = [body stringByReplacingOccurrencesOfString:img[@"ref"] withString:imgHTML]; // 4.取出新闻标题
NSString *title = news[@"title"];
// 5.取出新闻的时间
NSString *time = news[@"ptime"]; // 头部内容
NSString *header = [NSString stringWithFormat:@"<div class=\"title\">%@</div><div class=\"time\">%@</div>", title, time];
html = [NSString stringWithFormat:@"%@%@", header, html]; // 链接mainBundle中的CSS文件
NSURL *cssURL = [[NSBundle mainBundle] URLForResource:@"news" withExtension:@"css"];
html = [NSString stringWithFormat:@"%@<link rel=\"stylesheet\" href=\"%@\">", html, cssURL]; // 5.加载网页内容
[webView loadHTMLString:html baseURL:nil];
} @end
UIWebView加载POST请求
NSURL *url = [NSURL URLWithString: @"http://your_url.com"];
NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request]
iOS UI基础-15.0 UIWebView的更多相关文章
- iOS UI基础-4.0应用程序管理
功能与界面 功能分析: 以九宫格的形式展示应用信息 点击下载按钮后,做出相应的操作 步骤分析: 加载应用信息 根据应用的个数创建对应的view 监听下载按钮点击 整个应用界面: 程序实现 思路 UI布 ...
- iOS UI基础-17.0 UILable之NSMutableAttributedString
在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求.之前在网上找了一些资料,有的是重绘UILabel的textLayer,有的是用html5实现的,都比较麻烦 ...
- iOS UI基础-9.0 UITableView基础
在iOS中,要实现表格数据展示,最常用的做法就是使用UITableView.UITableView继承自UIScrollView,因此支持垂直滚动,而且性能极佳. UITableView有两种样式: ...
- iOS UI基础-7.0 UIScrollView
概述 移动设备的屏幕大小是极其有限的,因此直接展示在用户眼前的内容也相当有限.当展示的内容较多,超出一个屏幕时,用户可通过滚动手势来查看屏幕以外的内容,普通的UIView不具备滚动功能,不能显示过多的 ...
- iOS UI基础-3.0图片浏览器及plist使用
需求: 1.显示当前图片序号/总图片数 2.显示图片 3.上一张图片.下一张图片转换 4.显示图片描述 下面用代码来实现 // // UYViewController.m // 3.0图片查看器 // ...
- iOS UI基础-19.0 UICollectionView
直接上代码,说明请看注释吧 1.继承三个代理 UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateF ...
- iOS UI基础-16.0 UIButton
回归自然,UIButton是我们使用最频烦的一个控件.下面,对该控件的一些常用方法进行一些总结. UIButton *payStateBtn = [UIButton buttonWithType:UI ...
- iOS UI基础-13.0 数据存储
应用沙盒 每个iOS应用都有自己的应用沙盒(应用沙盒就是文件系统目录),与其他文件系统隔离.应用必须待在自己的沙盒里,其他应用不能访问该沙盒 应用沙盒的文件系统目录,如下图所示(假设应用的名称叫Lay ...
- iOS UI基础-12.0 Storyboard
storyboard创建控制器 1.先加载storyboard文件(Test是storyboard的文件名) UIStoryboard *storyboard = [UIStoryboard stor ...
随机推荐
- Java的各种打包方式
JAR (Java Archive file) 包含内容:class.properties文件,是文件封装的最小单元:包含Java类的普通库.资源(resources).辅助文件(auxiliary ...
- POJ 2027 - No Brainer
Description Zombies love to eat brains. Yum. Input The first line contains a single integer n indica ...
- [No0000C9]神秘的掐指一算是什么?教教你也会
很多朋友看到传说中诸葛亮以及那些聪明人掐指一算,惊叹不已.那些人以“察天地之理.通鬼神之志”,每次占卜时,做一大堆的神秘仪式,然后掐指一算,便大有“乾坤尽收在手”的感觉.在普通人眼里,他们的手神秘异常 ...
- 在ubuntu系统中,python依赖存放的路径
你在使用python,之后你想给python安装一些第三方库,如tensorflow或者tensorrt,那么这些包存放在哪个路径下呢? 该目录下: /usr/local/lib/python3.5/ ...
- Sleep 等待连接攻击
Sleep The thread is waiting for the client to send a new statement to it. https://dev.mysql.com/doc/ ...
- new malloc 区别
http://www.cplusplus.com/reference/cstdlib/malloc/ http://www.cplusplus.com/reference/new/operator%2 ...
- 单KEY业务,数据库水平切分架构实践 | 架构师之路
https://mp.weixin.qq.com/s/8aI9jS0SXJl5NdcM3TPYuQ 单KEY业务,数据库水平切分架构实践 | 架构师之路 原创: 58沈剑 架构师之路 2017-06- ...
- PHP-之POSIX系列函数和兼容Perl系列函数比较
PHP有两种正则系列函数 POSIX 系列和兼容Perl系列的函数 在PHP大于5.3使用POSIX系列函数会报E_DEPRECATED 错误, POSIX系列函数在大于5.3版本不建议使用,PHP7 ...
- spark学习笔记3
Spark 支持在集群范围内将数据集缓存至每一个节点的内存中,可避免数据传输,当数据需要重复访问时这个特征非常有用,例如查询体积小的“热”数据集,或是运行如 PageRank 的迭代算法.调用 cac ...
- jquery基础学习之DOM篇(二)
在此之前请牢记,jquery 是一个合集对象!!!! 1.节点创建 js创建方法: 创建元素:document.createElement 设置属性:setAttribute 添加文本:innerHT ...