美文网首页
UIWebView 教程

UIWebView 教程

作者: solozyx | 来源:发表于2016-08-12 11:20 被阅读121次

1.UIWebView加载远程网页

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forward;
@end
@implementation ViewController

- (IBAction)back:(id)sender {
    [self.webView goBack];
}

- (IBAction)forward:(id)sender {
    [self.webView goForward];
}

- (IBAction)refresh:(id)sender {
    [self.webView reload];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Native(OC+Swift) + HTML5
    
    self.webView.delegate = self;
    NSString *urlString = @"http://www.jianshu.com/users/468d1f0192cb/latest_articles";
    NSURL *url = [NSURL URLWithString:urlString];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

#pragma mark - <UIWebViewDelegate>

/**
 * 每当webView即将发送一个请求之前,都会调用这个方法
 * 返回YES:允许加载这个请求
 * 返回NO:禁止加载这个请求
 */
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{
    NSLog(@"%s", __func__);
    return YES;
}


- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"%s", __func__);
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"%s", __func__);
    self.backItem.enabled = webView.canGoBack;
    self.forward.enabled = webView.canGoForward;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"%s", __func__);
    self.backItem.enabled = webView.canGoBack;
    self.forward.enabled = webView.canGoForward;
}

@end

// -[ViewController webView:shouldStartLoadWithRequest:navigationType:]
// -[ViewController webViewDidStartLoad:]
// -[ViewController webViewDidFinishLoad:]

UIWebView简单应用.png

2.UIWebView加载本地资源

test.html

<html>
    <meta charset="UTF-8">
    <body>
        电话号码:13211112222
        网站:http://www.baidu.com
    </body>
</html>
// 网页内容缩小到适应整个设备屏幕
self.webView.scalesPageToFit = YES;

// 检测各种特殊的字符串 : 比如电话、网站
self.webView.dataDetectorTypes = UIDataDetectorTypeAll;

[self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]]];

self.webView.scrollView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:@"/Users/admin/Desktop/OC常用数据类型.ppt"]]];
[self.webView loadData:<#(NSData *)#> MIMEType:<#(NSString *)#> textEncodingName:<#(NSString *)#> baseURL:<#(NSURL *)#>];
NSString *htmlString = @"<html><body><div style=\"color: red; font-size:10px; border:1px solid blue;\">哈哈哈哈哈</div></body></html>";
[self.webView loadHTMLString:htmlString
                     baseURL:nil];

3.OC调用网页JavaScript代码

index.html

<html>
    <head>
        <meta charset="UTF-8">
        <title>第一个网页</title>
        <script>
            function openCamera(){
                location.href = 'solozyx://openCamera';
            }
        </script>
    </head>
    
    <body>
        电话:10086
        <button style="background: red; width:100px; height:30px;" onclick="openCamera();">打开相机</button>
        <br>
        <a href="http://www.baidu.com">百度</a>
    </body>
</html>

ViewController.m

#import <JavaScriptCore/JavaScriptCore.h>

@interface ViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];
}

- (void)call{
    NSLog(@"%s", __func__);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];
}

- (void)openCamera{
    NSLog(@"%s", __func__);
}


#pragma mark - <UIWebViewDelegate>

/**
 * 通过这个方法完成JS调用OC
 * JS和OC交互的第三方框架:WebViewJavaScriptBridge
 */
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{
    
    NSLog(@"%s",__func__);
    
    NSString *urlString = request.URL.absoluteString;
    NSString *scheme = @"solozyx://";
    
    if ([urlString hasPrefix:scheme]) {
        NSString *methodName = [urlString substringFromIndex:scheme.length];
        NSLog(@"methodName = %@",methodName); // methodName = openCamera
        [self performSelector:NSSelectorFromString(methodName) withObject:nil];
        NSLog(@"想调用OC的方法,不加载其他请求");
        return NO;
    }
    
    NSLog(@"想加载其他请求,不是想调用OC的方法");
    
    return YES;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [webView stringByEvaluatingJavaScriptFromString:@"alert(100);"];
    
    // 利用JS获得当前网页的标题
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title;"];
    NSLog(@"%@", self.title);
    
    NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"openCamera();"];
    NSLog(@"%@", result);
}

@end

4.自定义协议调用OC代码

index.html

<html>
    <head>
        <meta charset="UTF-8">
        <title>第一个网页</title>
        <script>
            function sendMessage(){
                location.href = 'solozyx://sendMessage_number2_?200&300';
            }
        </script>
    </head>
    
    <body>
        <button style="background: gray; width:100px; height:30px;" onclick="sendMessage();">发短信</button>
    </body>
</html>

去除Xcode编译警告

#import "ViewController.h"

// 去除Xcode编译警告
//#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//#pragma clang diagnostic pop

@interface ViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];
}

- (void)sendMessage:(NSString *)number number2:(NSString *)number2{
    NSLog(@"%s %@ %@", __func__, number, number2);
}

#pragma mark - <UIWebViewDelegate>
/**
 * 通过这个方法完成JS调用OC
 * JS和OC交互的第三方框架:WebViewJavaScriptBridge
 */
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *urlString = request.URL.absoluteString;
    NSLog(@"urlString = %@",urlString);
    // urlString = solozyx://sendMessage_number2_?200&300
    
    
    NSString *scheme = @"solozyx://";
    
    if ([urlString hasPrefix:scheme]) {
        // 获得协议后面的路径
        NSString *pathString = [urlString substringFromIndex:scheme.length];
        NSLog(@"pathString = %@",pathString);
        // pathString = sendMessage_number2_?200&300
        
        // 利用?切割路径
        NSArray *subpaths = [pathString componentsSeparatedByString:@"?"];
        // 方法名
        NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
        NSLog(@"methodName = %@",methodName);
        // methodName = sendMessage:number2:
        
        // 参数  200&300
        NSString *param = [subpaths lastObject];
        NSArray *subparams = nil;
        if ([param containsString:@"&"]) {
            subparams = [param componentsSeparatedByString:@"&"];
        }
        
        // 取出前面的2个参数
        NSString *firstParam = [subparams firstObject];
        NSString *secondParam = subparams.count <= 1 ? nil : [subparams lastObject];
        
        NSLog(@"调用OC的方法,不加载其他请求");
        [self performSelector:NSSelectorFromString(methodName) withObject:firstParam withObject:secondParam];
        // -[ViewController sendMessage:number2:] 200 300
        
        return NO;
    }
    
    NSLog(@"想加载其他请求,不是想调用OC的方法");
    
    return YES;
}

@end

相关文章

网友评论

      本文标题:UIWebView 教程

      本文链接:https://www.haomeiwen.com/subject/xuolsttx.html