首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >UIWebview与OC交互以及加载失败

UIWebview与OC交互以及加载失败

作者头像
Python疯子
发布2018-09-06 16:01:30
1.1K0
发布2018-09-06 16:01:30
举报
文章被收录于专栏:Python疯子Python疯子Python疯子

Simulator Screen Shot 2016年4月16日 00.27.57.png

One、UIWebView加载静态页面

做APP时,我们会展示静态页面,或与静态页面交互

self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height - 20)];
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath                                 encoding:NSUTF8StringEncoding  error:nil];
[self.webView loadHTMLString:htmlCont baseURL:baseURL];
[self.view addSubview: _webView];

与APP交互时,可以在静态页面中加如下代码

  <button id="btn_submit" onclick="Login('参数1')">返回</button>

在APP调用的文件中,

<blockquote>

先导入头文件 #import <JavaScriptCore/JavaScriptCore.h>

遵守UIWebView的代理 <UIWebViewDelegate>

</blockquote>

JSContext *context = [_webView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

context[@"Login"] = ^() {
     //  在这里处理你要做的事情
    NSArray *args = [JSContext currentArguments];
  
    //        NSString *strUrl = args[0];
    //        NSLog(@"%@",strUrl);        
    for (id obj in args) {
        NSLog(@"%@",obj);
    } 
};

Two、UIWebView加载网络页面和加载失败处理

之前写过浏览器网页与APP交互,在UIWebView内嵌与APP交互同样适用,开启穿越门

Simulator Screen Shot 2016年4月16日 01.20.24.png

导入文件 #import <JavaScriptCore/JavaScriptCore.h>

@interface ViewController ()
{
  NSURLConnection *theConnection;
}
@end
@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
UIWebView *myWebview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:myWebview];

NSURL *url = [NSURL URLWithString:@"https://itunesconnect.apple.com/"];
NSURLRequest *request =[NSURLRequest requestWithURL:url
                                        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                    timeoutInterval:10.0];
[myWebview loadRequest:request];


if (theConnection)
{
    [theConnection cancel];
// SAFE_RELEASE(theConnection);
    NSLog(@"safe release connection");
   }
theConnection= [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (theConnection) {
//  SAFE_RELEASE(theConnection);
    NSLog(@"safe release connection");
}

if ([response isKindOfClass:[NSHTTPURLResponse class]]){
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    if ((([httpResponse statusCode]/100) == 2)){
        NSLog(@"connection ok");
    }
    else{
        NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:nil];
        if ([error code] == 404){
            NSLog(@"404");
            [self webViewFail];
        }
       else if ([error code] == 403){
            NSLog(@"403");
            [self webViewFail];
        }
    }
  }
 }

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
  {
if (theConnection) {
//  SAFE_RELEASE(theConnection);
    NSLog(@"safe release connection");
     [self webViewFail];
}
if (error.code == 22) //The operation couldn’t be completed. Invalid argument
{
    NSLog(@"22");
 [self webViewFail];
}
else if (error.code == -1001) //The request timed out.  webview code -999的时候会收到-1001
{
    NSLog(@"-1001");
 [self webViewFail];
}
else if (error.code == -1005) //The network connection was lost.
{
    NSLog(@"-1005");
 [self webViewFail];
}
else if (error.code == -1009) //The Internet connection appears to be offline
{
    NSLog(@"-1009");
     [self webViewFail];
}
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
/*
didFailLoadWithError中出现code = -999错误。
 错误原因:一个页面没有被加载完成之前,收到下一个请求。
  */ 
 CLog(@"error%@",error);

if ([error code] == NSURLErrorCancelled) {
    return;
}

 [self webViewFail];
}


- (void)webViewFail
 {
UILabel *content = [[UILabel alloc]initWithFrame:(CGRectMake(20, 100, 300, 100))];

NSString *originStr = @"Hello,中秋节!";
NSMutableAttributedString *attributedStr01 = [[NSMutableAttributedString alloc] initWithString: originStr];
[attributedStr01 addAttribute: NSForegroundColorAttributeName value: [UIColor blueColor] range: NSMakeRange(0, 4)];
//分段控制,第5个字符开始的3个字符,即第5、6、7字符设置为红色
[attributedStr01 addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range: NSMakeRange(4, 3)];

//赋值给显示控件label01的 attributedText
content.attributedText = attributedStr01;
[self.view addSubview:content];


// 这里为加载静态页面,进行展示错误信息
//   UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
 //   NSString *path = [[NSBundle mainBundle] bundlePath];
//   NSURL *baseURL = [NSURL fileURLWithPath:path];
//    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"webError" ofType:@"html"];
//    NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//    [webView loadHTMLString:htmlCont baseURL:baseURL];
//  [self.view addSubview: webView];
//     JS 调用 OC
//     1、首先导入库 JavaScriptCore.framework
//   JSContext *context = [webView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//   context[@"btnSubmit"] = ^() {            
//    NSLog(@"返回上一页");
//  };
 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.04.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • One、UIWebView加载静态页面
  • Two、UIWebView加载网络页面和加载失败处理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档