前端学习基地iOS学习iOS程序猿

H5学习07之webView与网页交互

2017-01-21  本文已影响79人  张不二01

本篇内容:

开发iOS程序的过程中,在用到网页的时候的交互,我分为两种:

一,在oc中改变网页内容:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/index.php?tn=monline_3_dg"]]];
    self.webView.delegate = self;
    self.webView.hidden = YES;
    self.view.backgroundColor = [UIColor blueColor];
    
    self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.indicatorView.center = CGPointMake(self.view.bounds.size.width*0.5, self.view.bounds.size.height*0.5);
    [self.view addSubview:_indicatorView];
    [self.indicatorView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //找到标签的id,然后用js取出这个标签,并移除即可,然后使用下面的这个方法调用js代码就搞定了
    [webView stringByEvaluatingJavaScriptFromString:@"var div = document.getElementById('logo');div.parentNode.removeChild(div);"];
    [self.indicatorView removeFromSuperview];
    self.webView.hidden = NO;
    
}
二,在网页中调用ios的某些功能
//网页中代码:(css代码请自行添加)
<div class="container">
    <div><button onclick="openCamera()">打开摄像头</button></div>
    <div><button onclick="openAlbum()">打开相册</button></div>
    <div><button onclick="call10086()">打电话给10086</button></div>
</div>

<script type="text/javascript">
    //每当有网页跳转的时候其实都是修改了window的location属性,而oc中webview的监听方法也会监听这个属性变化
    //那我们修改了这个属性之后,设置一个自定义的协议,就可以进行监听,然后根据协议内容在oc中做出相应的操作
    function openCamera() {
        window.location.href = "imp://openCamera";
    }
    function openAlbum() {
        window.location.href = "imp://openAlbum";
    }
    function call10086() {
        window.location.href = "imp://call10086";
    }
</script>=
//oc中代码:
- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"OpenCamera" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    self.webView.delegate = self;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if ([request.URL.absoluteString containsString:@"imp://"]) {
//        NSLog(@"自定义协议---%@",request.URL.absoluteString);
        NSString *operation = [request.URL.absoluteString substringFromIndex:@"imp://".length];
//        NSLog(@"需要做的操作是:%@",operation);
        if ([operation isEqualToString:@"openCamera"]) {
            //当拦截到相应的操作命令的时候执行自定义的相应操作
            [self openCamera];
        }else if ([operation isEqualToString:@"openAlbum"]){
            [self openAlbum];
        }else if ([operation isEqualToString:@"call10086"]){
            [self call10086];
        }
    }
    return YES;
}
- (void)openCamera{
    NSLog(@"001");
    //相机在模拟器中是不起作用的
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];
}
- (void)openAlbum{
    NSLog(@"002");
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}
- (void)call10086{
    NSLog(@"003");
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];
}
三,网页新闻页面的简单制作
网易新闻页面.gif

代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    //地址
//    http://c.m.163.com/nc/article/BM22UB6505188ANB/full.html
    
    //发送网络请求,请求到数据
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://c.m.163.com/nc/article/BM22UB6505188ANB/full.html"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error || !data ) return;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        取出数据
        NSDictionary *resultDict = dict[@"BM22UB6505188ANB"];
        //取出其中的html的body字符串
        __block NSMutableString *htmlStr = resultDict[@"body"];
//        NSLog(@"%@", resultDict);
        
        //进行图片的替换即可
        NSArray *imageArr = resultDict[@"img"];
        [imageArr enumerateObjectsUsingBlock:^(NSDictionary *imageStr, NSUInteger idx, BOOL * _Nonnull stop) {
//            NSLog(@"%@------\n", imageStr);
            NSString *modifiedImgStr = [NSString stringWithFormat:@"![](%@)",imageStr[@"src"]];
//            NSLog(@"zhangdanfeng-------%@",modifiedImgStr);
            
//            NSLog(@"%@",imageStr[@"ref"]);
            
            htmlStr = (NSMutableString *)[htmlStr stringByReplacingOccurrencesOfString:imageStr[@"ref"] withString:modifiedImgStr];
//            NSLog(@"%@",htmlStr);
        }];
//        self.webView.scalesPageToFit = YES;
        [self.webView loadHTMLString:htmlStr baseURL:nil];
        
    }];
    [dataTask resume];
}
上一篇 下一篇

猜你喜欢

热点阅读