基于UIWebView混合编程

简介

UIWebView可以加载网页,还可以加载html、pdf、txt等多种格式文件.
混合编程: 指同时使用原生控件和UIWebview展示页面.唐巧在《iOS开发进阶》中说道:

合理的使用该方案,即可以保证页面的流畅交互效果,又有Web页面良好的动态更新和多平台复用的优势.

应用场景:
1. 页面排版复杂,用户交互简单;
2. 界面需频繁更新;

核心API

1. 加载网页

分为三种初始化方法:

- loadData:MIMEType:textEncodingName:baseURL:
- loadHTMLString:baseURL: // 加载本地HTML资源使用该方法而不是loadRequest(原因:使用该方法更为安全)
- loadRequest

loadData:MIMEType:textEncodingName:baseURL
data为文件数据(NSData),type为文件类型(NSString),encoding为编码方式(NSString),baseURL为资源路径(NSURL).// 加载data数据创建WebView.
loadHTMLString:baseURL:
htmlString是传入HTML,baseURL一般是传入[[NSBundle mainBundle] bundlePath]或者传入nil,那么baseURL代表什么呢?这篇文章中:iOS中UIWebView的使用详解提到baseURL是用于设置基础路径用于html中引用的文件等素材,也就是设置资源路径.// 加载本地HTML创建WebView
loadRequest.
加载请求创建WebView

2. UIWebViewDelegate

苹果文档-UIWebViewDelegate

-webView:shouldStartLoadWithRequest:navigationType:// Sent before a web view begins loading a frame. 在开始加载WebView之前(具体为loading a frame)进入该代理,返回NO则不加载该WebView.
-webViewDidStartLoad: // Sent after a web view starts loading a frame.开始加载WebView时进入该代理
-webViewDidFinishLoad:// 加载完毕
-webView:didFailLoadWithError:// 加载失败

3.交互

OC 调JS

// 执行JS方法
- (void)evaluateJavaScript:(NSString *)javaScriptString 
         completionHandler:(void (^)(id, NSError *error))completionHandler;
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;// 虽然该方法还没deprecated,但最好使用上一方法

JS 调OC

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
demo:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL * url = [request URL];
    if ([[url scheme] isEqualToString:@"gap"]) {
        // 通过URL进行传参
        if ([[url host] isEqualToString:@"jump"]) {

            ShopDetailViewController * issuedVC = [[ShopDetailViewController alloc] init];
            issuedVC.shopID = [[url valueForParameter:@"shopID"] intValue];
            [self.navigationController pushViewController:issuedVC animated:YES];
        }
    }

    return YES;
}

html端为

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <title>测试网页</title>
    </head>
    <body>
        <a href="gap://jump?invitingID=1">点击发送</a>
    </body>
</html>

ps: demo from 浅谈UIWebView,HTML5与Native的混合开发

4.基本属性

@property(nonatomic, readonly, strong) UIScrollView *scrollView;// 获取scrollView,只读属性,一般用于设置scrollView的代理以控制webView的滚动事件
@property(nonatomic, readonly, getter=isLoading) BOOL loading; // 判断是否正在加载中,只读属性
@property (nonatomic, readonly, retain) UIScrollView *scrollView; // 获取内置的scrollView,只读属性
@property (nonatomic) BOOL scalesPageToFit;// 是否缩放页面以适应屏幕大小,YES为可以缩放页面也就是可以响应用户的放大与缩小手势,NO代表不可缩放也就是不响应
@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);// 将哪些特殊数据类型设置为可链接格式,比如电话,邮件,地址,网址等.
@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0); // 是否可以使用内联播放器播放视频
@property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS(4_0);// 设置HTML5视频是否可以自动播放,还是需用户点击后才开始播放
@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS(5_0); // 是否支持AirPlay功能
@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0); // 是否在加载完页面后再对页面进行渲染,默认为NO
@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0);// indicating whether web content can programmatically display the keyboard.是否可以显示键盘(?:不知道理解的对不对),默认为YES

- (void)stopLoading;// 停止加载
- (void)reload;// 重新加载
- (void)goBack;// 返回上一级页面
- (void)goForward;// 向前访问页面
// 网页大小超出webView大小时,设置翻页时的展示方式
@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);
typedef NS_ENUM(NSInteger, UIWebPaginationMode) { 
UIWebPaginationModeUnpaginated, //不使用翻页效果 
UIWebPaginationModeLeftToRight, //将网页超出部分分页,从左向右进行翻页 
UIWebPaginationModeTopToBottom, //将网页超出部分分页,从上向下进行翻页 
UIWebPaginationModeBottomToTop, //将网页超出部分分页,从下向上进行翻页 
UIWebPaginationModeRightToLeft //将网页超出部分分页,从右向左进行翻页 
};

@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);// CSS的属性分页是可用还是忽略。默认是UIWebPaginationBreakingModePage 

@property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS(7_0);// 设置每一页的长度
@property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS(7_0);// 设置每一页的间距
@property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS(7_0);// 获取页数

Show me code

加载服务端网页

-(UIWebView *)remoteWebview
{
    if (!_webview) {

        _webview = [[UIWebView alloc] init];
        _webview.scalesPageToFit = YES;
        _webview.delegate = self;

        NSURL *url =[NSURL URLWithString:self.urlString];
        NSURLRequest *request =[NSURLRequest requestWithURL:url];
        [_webview loadRequest:request];

    }
    return _webview;
}

加载本地网页

- (UIWebView *)localWebView
{
    if (!_webView) {

        _webView = [[UIWebView alloc] init];
        _webView.scalesPageToFit = YES;
        _webView.delegate = self;

        NSURL *bundlePath = [[NSBundle mainBundle] bundlePath];
        NSString *filePath = [[bundlePath absolutePath] stringByAppendingPathComponent:@"index.html"];
        NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath  encoding:NSUTF8StringEncoding error:nil];
        [_webView loadHTMLString:htmlstring baseURL:bundlePath];
    }
    return _webView;
}

简单UIWebView

_webview = [[UIWebView alloc]  initWithFrame:CGRectMake(0, 0, 320, 480)];
_webview.scalesPageToFit = YES;
_webview.delegate = self;

NSURL *url =[NSURL URLWithString:@"http://blog.csdn.net/"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[_webview loadRequest:request];

WKWebView[待补]

In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to false if you render files that are not supposed to run JavaScript.

iOS8以后,最好使用WKWebView来替代UIWebview.提供更好的交互性.
苹果文档:这里

WebViewJavascriptBridge

github地址:https://github.com/marcuswestin/WebViewJavascriptBridge

参考资料

Apple-UIKit-UIWebView
文档-翻译

UIWebView与JS的深度交互
浅谈UIWebView,HTML5与Native的混合开发

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值