专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
UIWebView 简介
ATS配置:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
UIWebView
是iOS
内置的浏览器控件- 系统自带的
Safari
浏览器就是通过UIWebView
实现的 UIWebView
不但能加载远程的网页资源,还能加载绝大部分的常见文件如:html\htm
、pdf
、doc
、ppt
、txt
、mp4
等
UIWebView
使用
- 加载本地资源
// webView加载本地资源 NSURL *url = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; [self.webView loadRequest:request];
UIWebView
默认会检测电话号码,在真机上点击会直接拨打电话,在模拟器上无法拨打电话号码UIWebView
自动检测网页中的电话、邮件地址、链接self.webView.dataDetectorTypes = UIDataDetectorTypeAll;
UIWebView
开启放大和缩小// 开启放大和缩小 self.webView.scalesPageToFit = YES;
OC
中调用 JavaScript
- 如何在
OC
中调用JavaScript
代码 使用UIWebView
的stringByEvaluatingJavaScriptFromString
方法即可[self.webView stringByEvaluatingJavaScriptFromString:@"game.chessboard.drawPlanes();"];
OC
中调用JavaScript
代码获取返回值:- 1.在
index.html
中定义一个带返回值的JavaScript
方法<script> function test() { return "12345"; } </script>
- 2.在
OC
中调用这个方法NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"test();"]; NSLog(@"result: %@", result);
- 1.在
JavaScript
中调用 OC
的方法
URL
格式:scheme://[hostname][:port]/path
scheme
: 协议类型- http
- https
- ftp
- file
hostname
: 主机- 是指存放资源的服务器的域名系统
port
: 端口号path
: 路径- 由零或多个“/”符号隔开的字符串,一般用来表示主机上的一个目录或文件地址
JavaScript
调用OC
需要自定义协议,然后在OC
中拦截自定义协议- 在
index.html
中自定义协议:<a href="czbk:///showMessage:/下载完毕/YES">JS调用OC代码</a>
在
ViewController
中实现UIWebView
的shouldStartLoadWithRequest:navigationType
代理方法- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // 自定义协议,不需要去加载这个请求 // <a href="czbk:///showMessage/下载完毕">JS调用OC代码</a> if ([request.URL.scheme isEqualToString:@"czbk"]) { return NO; } return YES; }
获取
自定义协议
中的需要调用OC
方法
的名称
和参数
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // 自定义协议,不需要去加载这个请求 // <a href="czbk:///showMessage/下载完毕">JS调用OC代码</a> if ([request.URL.scheme isEqualToString:@"czbk"]) { // 获取方法名称 NSString *methodName = request.URL.pathComponents[1]; // 参数 NSString *parameter = request.URL.pathComponents[2]; // 将方法名称转成selector SEL method = NSSelectorFromString(methodName); // 判断当前类是否存在对应方法 if ([self respondsToSelector:method]) { // 执行对应的方法 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self performSelector:method withObject:parameter]; #pragma mark diagnostic pop } return NO; } return YES; } /** * OC 方法,弹出提示框 * @param msg 消息 */ - (void)showMessage:(NSString *)msg { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil]; [alertView show]; }