UIWebView使用浅析

概述

UIWebView是iOS sdk中一个最常用的控件,是内置的浏览器控件,我们可以用它来浏览网页、打开文档等等。可以在不发布版本的情况下改变其显示的内容。今天和大家一起看下UIWebView的使用。

本文包括下面内容

  • UIWebView的几种加载方式
  • Cookie的读取和赋值
  • UIWebView和JavaScript交互

一.UIWebView的几种加载方式

大体说来,给UIWebView添加内容的方式分两种:

  1. 一种是从一个文件加载,类似在浏览器上输入URL或本地文件路径

  2. 一种是将一段HTML原代码,直接赋给UIWebView

1.1 直接加载本地的HTML文件
NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; 
[self.myWebview loadRequest:[NSURLRequest requestWithURL:url]];
1.2 直接加载本地的HTML文件
NSString *htmlPath = [[[NSBundle mainBundle] bundlePath]
    stringByAppendingPathComponent:@"index.html"];
[self.myWebview loadRequest:[NSURLRequest requestWithURL:
    [NSURL fileURLWithPath:htmlPath]]];
1.3 加载html字符串(可以加载全部或者部分html文件)
NSString *htmlPath = [[[NSBundle mainBundle] bundlePath]
    stringByAppendingPathComponent:@"index.html"];

NSString *htmlString = [NSString stringWithContentsOfFile: htmlPath
                                    encoding:NSUTF8StringEncoding 
                                    error:NULL];
[self.myWebview loadHTMLString:htmlString baseURL:[NSURL
    fileURLWithPath:htmlPath]];

二.Cookie的读取和赋值

2.1 Cookie的读取
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]; 
NSHTTPCookie *cookie;
for (id c in cookies){
    if ([c isKindOfClass:[NSHTTPCookie class]]) {
        cookie=(NSHTTPCookie *)c;
        NSLog(@"%@: %@", cookie.name, cookie.value); }
}
2.2 Cookie的赋值

注:如果提供的属性是无效的,初始化Cookie对象为nil。

NSHTTPCookieValue,NSHTTPCookieName,NSHTTPCookieDomain,NSHTTPCookiePath是必选的

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    
[cookieProperties setObject:@"test" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"cookiesid" forKey:NSHTTPCookieName];
[cookieProperties setValue:@".baidu.com" forKey:NSHTTPCookieDomain];
[cookieProperties setValue:@"/" forKey:NSHTTPCookiePath];
    
NSHTTPCookie *cookie = [[NSHTTPCookie alloc] initWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

request还可以这样设置cookie

[request setHTTPShouldHandleCookies:YES];
[request setValue:[NSString stringWithFormat:@"%@=%@", [cookie name], [cookie value]] forHTTPHeaderField:@"Cookie"];

三.UIWebView和JavaScript交互

IOS中UIWebView和JavaScript交互可以分为两种:

  • 客户端传递给JS一些数据
  • JS向客户端请求一些本地操作
3.1 客户端传递给JS一些数据

客户端向JS传递数据,通过插入JS方法来实现,UIWebView的这个方法可以完成这项功能。

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

实例代码:可以看到html页面有一个由js弹出的弹窗

NSString *jsCode = [NSString stringWithFormat:@"alert("html页面加载成功!");"];
[myWebView stringByEvaluatingJavaScriptFromString:jsCode];

3.2 JS向客户端请求一些本地操作

这里的实现主要是通过对UIWebView的delegate方法进行处理来实现的。UIWebViewDelegate有这个一个方法

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

当一个web视图开始加载一个frame的时候会触发它。看起来很符合我们的需求。我们可以在页面里创建一个iframe,使用js代码去改变它的src来触发这个调用,从而实现js对Objc的调用。

实例代码:

html代码:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <script>
            var JSTest = {
                JSTest_SCHEME : "app",
                _hiddenFrame: null,
                
                createIframeForCallObjc : function () {
                    _hiddenFrame = document.createElement("iframe");
                    _hiddenFrame.style.display = 'none';
                    document.documentElement.appendChild(_hiddenFrame);
                },
                
                callObjcFun : function (funName, args) {
                    _hiddenFrame.src = JSTest.JSTest_SCHEME + "://" + funName;
                    _hiddenFrame.dataset['args'] = JSON.stringify(args);
                },
                
                getJSData : function () {
                    return _hiddenFrame.dataset['args']||"test";
                }
            };
        </script>
        
        <h1>Hello UIWebView!</h1>
        <input type="button" value="click" onclick="JSTest.callObjcFun('login',['xiaohan',666666])" id="testBtn" />
        <script>
            JSTest.createIframeForCallObjc();
        </script>
    </body>
</html>

UIWebViewDelegate处理

- (BOOL)webView:(UIWebView *)webView 
        shouldStartLoadWithRequest:(NSURLRequest *)request
        navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if ([[url scheme] isEqualToString:@"app"]) {
        if ([[url host] isEqualToString:@"login"]) {
            //后续处理代码
            NSString *params = [myWebView stringByEvaluatingJavaScriptFromString:@"JSTest.getJSData();"];
            NSLog(@"%@",params);
        } else {
            
        }
        return NO;
    }
    return YES;
}

通过在得到webview所要加载的url来判断是否是需要处理的条件,只需要定义好相关的协议串即可。


后记:这里只是浅析了UIWebView的一些使用方法,欢迎大家指导和交流!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容