您的位置:首页 > 移动开发

UIWebView 本地加载网页和文件(图片素材,js,css)(功能插件化)

2017-05-09 15:52 591 查看

技术思想就是先将开发完成的html功能打包压缩(zip)放在服务器上,移动端使用某个功能时就下载对应的压缩文件,然后移动端解压使用对应的网页文件。为了体验效果比较好,所以将这些放在本地,至于原生和网页之间的交互,下面代码里面也有。

1.建议将UIWebView 所在的控制器封装重写

#pragma mark - UIWebViewDelegate

//开始加载

- (BOOL)webView:(UIWebView *)awebView shouldStartLoadWithRequest:(NSURLRequest
*)request navigationType:(UIWebViewNavigationType)navigationType

{

    NSString* scheme = [[requestURL]scheme];

    //判断是不是https

    if ([schemeisEqualToString:@"https"]) {

       
//如果是https:的话,那么就用NSURLConnection来重发请求。从而在请求的过程当中吧要请求的URL做信任处理。

        if (!self.isAuthed) {

            NSURLConnection* conn = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];

            [conn start];

            [awebView stopLoading];

            returnNO;

        }

    }

    returnYES;

}

//设置webview的title为导航栏的title

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

    self.title = [webViewstringByEvaluatingJavaScriptFromString:@"document.title"];

    CGRect frame = webView.frame;

    CGSize fittingSize = [webViewsizeThatFits:CGSizeZero];

    frame.size = fittingSize;

    webView.frame = frame;

    

    JSContext *context = [self.webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    /**

     *  弹出提示

     *

     *  @param alertTitle   <#alertTitle description#>

     *  @param alertMessage <#alertMessage description#>

     *

     *  @return <#return value description#>

     */

    context[@"PDAlert"] = ^(NSString * alertTitle,NSString * alertMessage){

        dispatch_async(dispatch_get_main_queue(), ^{

            //

            [selfPDAlertViewWithTitle:alertTitlemessage:alertMessagecancelButtonTitle:@"确定"otherButtonTitles:nil];

            

        

        });

        

    };

    

    

    context[@"PDGoBack"] = ^(){

        dispatch_async(dispatch_get_main_queue(), ^{

            //

            [selfbackNative];

        });

        

    };

    

    context[@"PDGetMap"] = ^(){

        dispatch_async(dispatch_get_main_queue(), ^{

            

        });

    };

}

#pragma mark ==========弹出提示框

-(void)PDAlertViewWithTitle:(NSString *)Title message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)Titles{

    UIAlertView * alert = [[UIAlertViewalloc]initWithTitle:Titlemessage:messagedelegate:selfcancelButtonTitle:cancelButtonTitleotherButtonTitles:Titles,nil];

    [alert show];

}

#pragma mark ================= NSURLConnectionDataDelegate <NSURLConnectionDelegate>

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace
*)protectionSpace

{

    return [protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust];

}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge
*)challenge

{

    if ([challengepreviousFailureCount] ==0) {

        self.isAuthed =YES;

       
//NSURLCredential 这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。

        NSURLCredential *cre = [NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];

        [challenge.senderuseCredential:creforAuthenticationChallenge:challenge];

    }

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError
*)error

{

    NSLog(@"网络不给力");

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response

{

    self.isAuthed =YES;

    //webview 重新加载请求。

    [self.webViewloadRequest:self.request];

    [connection cancel];

}

#pragma mark - 添加关闭按钮

- (void)addLeftButton

{

    self.navigationItem.leftBarButtonItem =self.backItem;

}

//点击返回的方法

- (void)backNative

{

   
//判断是否有上一层H5页面

    if ([self.webViewcanGoBack])
{

        //如果有则返回

        [self.webViewgoBack];

       
//同时设置返回按钮和关闭按钮为导航栏左边的按钮

        self.navigationItem.leftBarButtonItems
= @[self.backItem,self.closeItem];

    } else {

        [selfcloseNative];

    }

}

//关闭H5页面,直接回到原生页面

- (void)closeNative

{

    [self.navigationControllerpopViewControllerAnimated:YES];

}

#pragma mark - init

- (UIBarButtonItem *)backItem

{

    if (!_backItem) {

        _backItem = [[UIBarButtonItemalloc]init];

        UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

       
//这是一张“<”的图片,可以让美工给切一张

        UIImage *image = [UIImageimageNamed:@"back"];

        [btn setImage:imageforState:UIControlStateNormal];

//        [btn setTitle:@"返回" forState:UIControlStateNormal];

        [btn addTarget:selfaction:@selector(backNative)forControlEvents:UIControlEventTouchUpInside];

        [btn.titleLabelsetFont:[UIFontsystemFontOfSize:17]];

        [btn setTitleColor:C_blueColorforState:UIControlStateNormal];

        //字体的多少为btn的大小

        [btn sizeToFit];

        //左对齐

        btn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;

       
//让返回按钮内容继续向左边偏移15,如果不设置的话,就会发现返回按钮离屏幕的左边的距离有点儿大,不美观

        btn.contentEdgeInsets =UIEdgeInsetsMake(0, -15,0,0);

        btn.frame =CGRectMake(0,0,40,40);

        _backItem.customView = btn;

    }

    return_backItem;

}

- (UIBarButtonItem *)closeItem

{

    if (!_closeItem) {

        _closeItem = [[UIBarButtonItemalloc]initWithTitle:@"关闭"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(closeNative)];

    }

    return_closeItem;

}

2.继承上面的类,并创建初始化UIWebView

self.webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height-64)];

    self.webView.delegate =self;

//    self.webView.scrollView.bounces = NO;

    //        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Book" ofType:@"html"];

    NSString *filePath =self.webUrl;

    NSString *htmlString = [NSStringstringWithContentsOfFile:filePathencoding:NSUTF8StringEncodingerror:nil];

    NSArray *doc =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *docPath =[docobjectAtIndex:0];

    NSString * BookPath = [[NSStringalloc]initWithFormat:@"%@/ShowModule/%@",docPath,self.FileName];

    //        BookPath = [[NSString alloc] initWithFormat:@"%@/js",BookPath];

    NSString *path = [[NSBundlemainBundle]bundlePath];

    NSURL *baseURL = [NSURLfileURLWithPath:BookPath];

    

    [self.webViewloadHTMLString:htmlStringbaseURL:baseURL];

    [self.viewaddSubview:self.webView];

3.html部分代码(一般js和css都会分开写)

<!--模板页面,所有的页面同意使用此模板-->

<!DOCTYPE html>

<html>

<head>

<metacharset="UTF-8">

<title>推广</title>

<metaname="viewport"content="width=device-width,
initial-scale=1,maximum-scale=1,user-scalable=no">

<metaname="apple-mobile-web-app-capable"content="yes">

<metaname="apple-mobile-web-app-status-bar-style"content="black">

<linkrel="stylesheet"type="text/css"href="app_reset.css"
/>

<linkrel="stylesheet"type="text/css"href="mui.min.css"
/>

<linkrel="stylesheet"type="text/css"href="common.css"
/>

<linkrel="stylesheet"href="spread.css"
/>

<styletype="text/css">

</style>

</head>

<body>

<divclass="mui-content">

<divclass="pageContent">

<divstyle="text-align: center;">

<ahref="/default.htm"><imgsrc="sign_icon.png"class="big_icon"
/></a>

</div>

<divid="register_div">

<pstyle="color: #A21E2E;text-align: center;font-size: 1.3rem;">用户注册(注册后您将成为【XXX】会员)</p>

<divclass="input_list">

<divclass="input_div">

<inputplaceholder="昵称"id="txtName_Register"
/>

</div>

<divclass="input_div">

<inputplaceholder="推荐人手机号"id="tuijian_txtPhone"
/>

</div>

<divclass="input_div">

<inputplaceholder="手机号(仅支持中国大陆)"id="txtPhone_Register"
/>

</div>

<divclass="input_div">

<inputtype="password"placeholder="密码(不少于6位)"id="tuijian_txtPassWord"
/>

</div>

<divclass="input_div">

<inputtype="password"placeholder="再次输入密码"id="sure_txtPassWord"
/>

</div>

<divclass="input_div">

<divclass="code_input">

<inputtype="text"placeholder="请输入验证码"id="cry"/>

</div>

<divclass="sign_code">获取验证码</div>

<divclass="mui-clearfix"></div>

</div>

</div>

<divclass="before_regist">

<buttontype="button"onclick="PDAlert('请输入','点击「注册」按钮,即代表你同意《XXXX协议》')"class="btn6"value="注册"id="registerBtn">注册</button>

</div>

<divclass="about_regist">

<p>点击「注册」按钮,即代表你同意《XXXX协议》</p>

</div>

</div>

<divclass="last_div">

<divclass="anzhuo"><imgsrc="android.png"/><span>安卓下载地址</span></div>

<divclass="apple"><imgsrc="apple.png"/><span>苹果下载地址</span></div>

<!--<div class="mui-clearfix"></div>-->

</div>

</div>

</div>

<scriptsrc="js/mui.min.js"type="text/javascript"charset="utf-8"></script>

<scriptsrc="js/common.js"type="text/javascript"charset="utf-8"></script>

<scripttype="text/javascript">

mui.init();

</script>

</body>

</html>

4.里面涉及到压缩,我直接用SSZipArchive来解压,可在网上直接下载,这里就不贴代码了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息