WebView和Html

说说WebView如何加载Html,css以及javascript

说一个网易新闻的实例:

先看看css和js中的内容

css

#mainTitle{
    text-align:center;
    font-size:20px;
    margin-top:25px;
    margin-bottom:8px;
}

#subTitle {
    color:gray;
    text-align:center;
}

img {
    width: 100%;
}

.time{
    margin-right:10px;
    margin-bottom:8px;
}

.imageDiv {
    text-align:center;
    color:gray;
    margin:8px 0;
}

js

window.onload = function() {

    var images = document.getElementsByTagName('img');

    console.log(images);

    for(var i = 0; i < images.length; i++) {
        //console.log(i + ":" + images[i]);
        var image = images[i];
        console.log(typeof image);
        image.onclick = function () {
            //alert('图片[' + this.alt + ']被点击');
            //window.location.href = 'https://www.baidu.com';
            window.location.href = 'flashloft://openCamera';
        }
    }
}

js定义了网页中的图片如果被点击,会执行事件函数。如果需要监听事件,需要设置UIWebView的Delegate

通过一个Http请求获得要加载的Html页面数据:

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //请求网易新闻页数据
    NSURL *url = [NSURL URLWithString:@"http://c.m.163.com/nc/article/BJ5NRE5T00031H2L/full.html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dataDict);

        [self showData:dataDict];
    }];
    [task resume];

    self.webView.delegate = self;
}

//请求完毕后拼接html代码,另外新建css文件和js文件在本地
- (void)showData:(NSDictionary*)dict {
    NSDictionary *allData = dict[@"BJ5NRE5T00031H2L"];

    NSString *bodyHtml = allData[@"body"];
    NSArray *imgs = allData[@"img"];

    for(NSDictionary *img in imgs) {
        NSString *ref = img[@"ref"];
        NSString *src = img[@"src"];
        NSString *alt = img[@"alt"];
        NSString *imageHtml = [NSString stringWithFormat:@"<div class=\"imageDiv\"><img src=\"%@\" alt=\"\%@\"></div><div>\%@</div>",src,alt,alt];
        bodyHtml = [bodyHtml stringByReplacingOccurrencesOfString:ref withString:imageHtml];
    }

    NSString *ptimeStr = allData[@"ptime"];
    NSString *titleStr = allData[@"title"];
    NSString *titleHtml = [NSString stringWithFormat:@"<div id=\"mainTitle\">\%@</div>",titleStr];
    NSString *sourceStr = allData[@"source"];
    NSString *subTitleHtml = [NSString stringWithFormat:@"<div id=\"subTitle\"><span class=\"ptime\">\%@</span><span>\%@</span></div>",ptimeStr,sourceStr];
    NSURL *cssPath = [[NSBundle mainBundle] URLForResource:@"news.css" withExtension:nil];
    NSString *cssHtml = [NSString stringWithFormat:@"<link href=\"\%@\" rel=\"stylesheet\">",cssPath.absoluteString];
    NSURL *jsPath = [[NSBundle mainBundle] URLForResource:@"news.js" withExtension:nil];
    NSString *jsHtml = [NSString stringWithFormat:@"<script src=\"\%@\"></script>",jsPath];
    NSString *currentHtml = [NSString stringWithFormat:@"<html><head><title>\%@</title>\%@\%@</head><body>\%@\%@\%@</body></html>",titleHtml,cssHtml,jsHtml,titleHtml,subTitleHtml,bodyHtml];

    [self.webView loadHTMLString:currentHtml baseURL:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    //这个方法可以扑捉到当前webView的请求,如果方法返回NO,webView不会进行任何跳转

    //如果webView捕捉到一个自定义的请求,可以执行一些方法,比如打开相机或相册等,这里打开系统相册
    [self checkMethod:request.URL.absoluteString];

    return YES;
}

//去除自定义请求的协议头,判断如果协议头包含‘flashloft://’,则去除协议头,根据剩下的字段转换成selector,找到对应的方法并执行
- (void)checkMethod:(NSString*)urlStr {
    NSString *urlHead = @"flashloft://";
    NSRange urlHeadRange = [urlStr rangeOfString:urlHead];

    if([urlStr containsString:urlHead]) {

        NSString *methodName = [urlStr substringFromIndex:urlHeadRange.length];
        NSLog(@"%@",methodName);

        SEL selector = NSSelectorFromString(methodName);
        [self performSelector:selector withObject:nil afterDelay:0.001];
    }
}

//访问相机的方法,记得在info.plist配置 Privacy - Photo Library Usage Description 权限
- (void)openPhotos {
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc]init];
    imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

@end

results matching ""

    No results matching ""