Web与OC交互——UIWebView

本篇内容:

  • 1, 在oc中改变网页内容
  • 2,在网页中调用ios的某些功能
  • 3,网页新闻页面的简单制作

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

  • 1, OC与网页交互:在oc中改变网页内容,也就是在oc中调用网页的代码,实现网页布局或者内容的改变,比如说在oc中删除网页的某些标签或者改变某些布局。
  • 2, 网页与OC交互:在网页中形式上调用oc代码,实现ios的某些网页无法实现的功能,比如点击网页的按钮实现打开相册或者打电话等
一,在oc中改变网页内容:
  • 1, 我们以打开百度手机网页为例, 在oc端利用oc与网页交互删除网页上的百度图标:
    思路:通过webView的代理方法,在网页加载完成之后,找到需要被操作的标签的id,然后用js取出这个标签,并移除,然后在oc中通过webView调用相应的代码执行刚才取出并移除标签的js语句即可

    • oc调用网页代码.gif
  • 代码如下:
- (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的某些功能
  • 我们以一个简单的网页为基础,在该网页上实现打开摄像头,相册和打电话功能:
    思路:通过webView的代理方法进行监听,每当有网页的window的location改变的时候就会监听到改变,我们只需要在网页中进行手动改变location这个属性,然后定义一个自己的协议,在oc里面判断筛选到我们自己的协议的时候执行相应的oc操作即可

    • 网页中调用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"]];
}
三,网页新闻页面的简单制作
  • 我这只是简单的把图片进行了替换,然后展示html内容,至于标题什么的可以直接通过标签添加,然后把标签拼接到对应的html的body字符串前面即可,或者其他方式也行,比较简单我这里就不演示了
    思路:发送网络请求请求到的json数据中含有html,把html中的对应信息在oc中进行拼接或者相应的更改,比如标题拼接,图片内容替换等等,之后通过webView展示html即可

网易新闻页面.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];
}


作者:ivanl001
链接:http://www.jianshu.com/p/00268ffd6ba9
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值