基于UIWebView的混合编程

来源:互联网 发布:硬盘数据彻底删除软件 编辑:程序博客网 时间:2024/05/22 10:33

 

UIWebView的加载方法

1.UIWebView的loadRequest:方法


__weak typeof (self)weakSelf=self;

    NSBlockOperation *operation=[NSBlockOperationblockOperationWithBlock:^{


        NSString *strUrl=_webViewImageURL;


        NSURLRequest *request=[NSURLRequestrequestWithURL:[NSURLURLWithString:strUrl]];

        

        [[NSOperationQueuemainQueue] addOperationWithBlock:^{


            [weakSelf.webViewloadRequest:request];

            

            [MBProgressHUDshowHUDAddedTo:_webViewanimated:YES];

            

        }];

    }];

    queue=[[NSOperationQueuealloc]init];

    [queueaddOperation:operation];


2.UIWebView的loadHTMLString::方法

将本地html文件内容嵌入webView


NSString *resourcePath = [ [NSBundlemainBundle] resourcePath];


     NSString *filePath  = [resourcePathstringByAppendingPathComponent:@"test.html"];


     NSString *htmlstring =[[NSStringalloc] initWithContentsOfFile:filePathencoding:NSUTF8StringEncodingerror:nil];


    [self.webViewloadHTMLString:htmlstring baseURL:[NSURLfileURLWithPath: [[NSBundlemainBundlebundlePath]]];



对于第二种加载方式,可以使用模板引擎渲染HTML界面

UIWebView通过 

- (void)loadHTMLString:(NSString *)string baseURL:(nullableNSURL *)baseURL;

这个接口接收一个html的内容.
由于html是不停变化的,所以我们不能用固定的HTML格式,所以我们需要一个模板引擎
模板引擎有MGTemplateEngine 和 GRMustache

关于GRMustache引擎 

1.它将模板内容放在另一个单独的文件中,方便日后更改

2.将原来一stringFormat格式固定的%@ 替换为{{ name }}形式

模板调整后变成了如下内容(文件名为template.html)

<HTML>

   <HEAD>

   </HEAD>

   <BODY>

<H1>{{ name }}</H1>

<P>{{ content }}</P>

</BODY>

</HTML>


然后我们在代码中将该文件读取到内存中(把fileName和bundlePath 用stringByAppendingPathComponent拼接起来,用stringWithContentsOfFile:读取文件),

再使用GRMustache的renderObject方法生成渲染后的HTML内容.


然后让UIWebView通过loadHTMLString:方法加载




0 0
原创粉丝点击