UIWebView基本使用

来源:互联网 发布:java会议室预定系统 编辑:程序博客网 时间:2024/04/30 07:27

#import "ViewController.h"


@interface ViewController ()

@property (nonatomic,weak)UIWebView * _webView;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

//    NSString *path = [[NSBundle mainBundle]pathForResource:@"关于" ofType:@"docx"];

//    //调本地文件用fileURLWithPath音频,音效都是这么调用

//    /**

//     *  text/plain 纯文本文件

//     */

//    NSURL *url = [NSURL fileURLWithPath:path];

    /**

     *  在沙箱中加载URL也可以直接用下面的方法

     */

    NSURL *url = [[NSBundlemainBundle]URLForResource:@"demo.html"withExtension:nil];

    NSString *mime = [selfmimeType:url];

    NSURLRequest *request = [NSURLRequestrequestWithURL:url];

    NSLog(@"文件类型是:%@",mime);

    //webView加载本地文件可以使用加载数据的方式

    //1.本地文件对应的数据

    //2.MIMEType

    //3.编码格式字符串

    //4.相对地址,一般加载本地文件不使用,可以在指定的baseURL中查找相关文件

    //5.如果要用UIWebView显示对应的文件,必须知道准确的MIMEType,但是不是所有格式的文件都可以通过本地数据的方式加载,即便是知道MIMEType

    //使用HTML开发应用

    /**

     *  优势:1.跨平台

       2.审批通过之后,终身不需要审批,UIWebView,用户访问的都是服务器,只需要在后台自己随时维护即可

     3.部分html可以用来制作新闻客户端的阅读部分

     弱势:

     1.没有办法利用硬件资源:加速器,手势等

     2.性能不好

     */

    [self setupUI];

    //以二进制的形式加载沙箱中的文件

    NSData *fileData = [NSDatadataWithContentsOfURL:url];

//    [__webView loadData:fileData MIMEType:mime textEncodingName:@"NSUTF8StringEncoding" baseURL:nil];

    /**

     *  检测所有数据类型

     */

    [__webViewsetDataDetectorTypes:UIDataDetectorTypeAll];

    /**

     *  注意MIME字符串不能出错否则加载不出来另外,编码格式只要使用UTF-8即可

     */


//    [__webView loadData:fileData MIMEType:mime textEncodingName:@"UTF-8" baseURL:nil];

    //直接加载完整的html字符串

    NSString * str =@"<html><head><title>最强王者</title></head><body><h2>网鱼网咖一起来更精彩</h2></body></html>";

    //部分字符串 <h1>你好呀</h1>

    NSString *str2 =@"<h1>你好呀</h1>";

//    [__webView loadHTMLString:str2 baseURL:nil];

    [__webView loadRequest:request];

}


#pragma mark 

- (void)setupUI{

    UIWebView *webView = [[UIWebViewalloc]init];

    webView.frame = self.view.bounds;

    [self.viewaddSubview:webView];

    __webView = webView;

    

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma mark -获取指定URLmimetype类型

- (NSString *)mimeType:(NSURL *)url{

    NSURLRequest *request = [NSURLRequestrequestWithURL:url];

    //同步

    NSURLResponse *response = nil;

    NSError *error = nil;

    NSURLConnection *connection = [NSURLConnectionsendSynchronousRequest:request returningResponse:&response error:&error];

    return response.MIMEType;

}


@end


0 0
原创粉丝点击