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 ...
随机推荐
- System.InvalidOperationException: 此实现不是 Windows 平台 FIPS 验证的加密算法的一部分。
x 昨天还好好地,然后清理一下电脑垃圾,就突然报这个错误了; 网上搜索了一下:找到解决方案了,但是由于底层知识的功力不够,至今未知具体怎么导致的... 解决方案↓ 进注册表 按Win+R运行reged ...
- JavaScript 引入方式 语言规范 语言基础 数据类型 常用方法 数组 if_else 比较运算符 for while 函数 函数的全局变量和局部变量 {Javascript学习}
Javascript学习 JavaScript概述 ECMAScript和JavaScript的关系 1996年11月,JavaScript的创造者--Netscape公司,决定将JavaScript ...
- 关于servelet入门介绍
servelet 容器 将前台的请求转发给后台 接受 http 表单, 后台处理操作数据库并且放回用户 .(粗劣) 手工编写第一个Servlet 1, 继承httpservlet 2, ...
- [No0000102]JavaScript-基础课程2
var bob = new Object(); bob.age = ; // 这一次我们已经添加了一个方法,setAge bob.setAge = function (newAge){ bob.age ...
- 在ubuntu系统中,python依赖存放的路径
你在使用python,之后你想给python安装一些第三方库,如tensorflow或者tensorrt,那么这些包存放在哪个路径下呢? 该目录下: /usr/local/lib/python3.5/ ...
- 从一个点的长度是多少说起(Talking started from the length of a point on the real number line)
From the perspective of analytical geometry, an interval is composed of infinitely many points, whil ...
- 一道与时间差有关的SQL面试题
题目: 一组通话记录(总共500万条):ID 主叫号码 被叫号码 通话起始时间 通话结束时间 通话时长1 98290000 0215466546656 2007-02-01 09:49:53.000 ...
- 进制转换 map
a_z = [i for i in map(chr, range(ord('a'), ord('z') + 1))]'''Address of var1 variable: 240ff24Addres ...
- PHP之魔术引号
什么是魔术引号 Warning 本特性已自 PHP5.3.0起废弃并将自PHP5.4.0起移除. 当打开,所有的'(单引号),"(双引号), (反斜线)和NULL 字符都会被自动加上一个反 ...
- [daily][centos][iptables][firewalld] firewalld的初步了解
CentOS7中默认使用firewalld代替了iptables . 接下来将对firewalld, 做一些初步的了解. 首先读一下, redhat的文档: https://access.redhat ...