UIWebView简单使用

来源:互联网 发布:专业看盘软件 编辑:程序博客网 时间:2024/04/28 12:47
一:基础知识

1:UIWebView是iOS内置的浏览器控件,系统自带的Safari浏览器就是通过UIWebView实现的.

UIWebView不但能加载远程的网页资源,还能加载绝⼤部分的常见文件 html\htm pdf、doc、ppt、txt  mp4 ......

MIME的英文全称是“Multipurpose Internet Mail Extensions” 多用途互联网邮件扩展,是一个互联网标准,最早应用于电子邮件系统,后来应 用到浏览器 .服务器通过说明多媒体数据的MIME类型,告诉浏览器发送的多媒体数据的类型,从而让浏览器知道接收到的信息哪些是MP3文件,哪些是Shockwave文件等等.

服务器将MIME标志符放入传送的数据中告诉浏览器使用哪种插件读取相关文件,MIME类型能包含视频、图像、文本、音频、应用程序等数据.

2:常用的属性和方法

//1:UIWebViewNavigationType枚举定义了页面中用户行为的分类typedef NS_ENUM(NSInteger, UIWebViewNavigationType) {        UIWebViewNavigationTypeLinkClicked,//用户触发了一个链接        UIWebViewNavigationTypeFormSubmitted,//用户提交了一个表单        UIWebViewNavigationTypeBackForward,//用户触击前进前进或返回按钮        UIWebViewNavigationTypeReload,//用户触击重新加载的按钮        UIWebViewNavigationTypeFormResubmitted,//用户重复提交表单        UIWebViewNavigationTypeOther//发生了其他行为    };//2. 加载内容关于分页显示几种不同类型typedef NS_ENUM(NSInteger, UIWebPaginationMode) {        UIWebPaginationModeUnpaginated,        UIWebPaginationModeLeftToRight,        UIWebPaginationModeTopToBottom,        UIWebPaginationModeBottomToTop,        UIWebPaginationModeRightToLeft    };//3.这个枚举决定了webView加载页面具有CSS属性时是使用页的样式还是以列的样式。typedef NS_ENUM(NSInteger, UIWebPaginationBreakingMode) {        UIWebPaginationBreakingModePage,//默认设置是这个属性,CSS属性以页样式。        UIWebPaginationBreakingModeColumn   //当UIWebPaginationBreakingMode设置这个属性的时候,这个页面内容CSS属性以column-break代替page-breaking样式。    };//类的代理@property(nonatomic, assign) id delegate//当前显示页面的URL请求@property(nonatomic, readonly, retain) NSURLRequest *request//当前网页是否是正在加载状态@property(nonatomic, readonly, getter=isLoading) BOOL loading//从当前网页是否能返回上一网页@property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack//从当前网页能否前进@property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward//网页内容是否自适应大小@property(nonatomic) BOOL scalesPageToFit//与当前web视图 相关联的滚动视图@property(nonatomic, readonly, retain) UIScrollView *scrollView//是否网页内容下载完毕才开始渲染web视图,默认为NO@property(nonatomic) BOOL suppressesIncrementalRendering//是否在web页面响应用户输入弹出键盘,默认为YES@property (nonatomic) BOOL keyboardDisplayRequiresUserAction//这个值决定了用内嵌HTML5播放视频还是用本地的全屏控制。为了内嵌视频播放,不仅仅需要在这个页面上设置这个属性,还必须的是在HTML中的video元素必须包含webkit-playsinline属性。默认使NO。@property(nonatomic) BOOL allowsInlineMediaPlayback//在iPhone和iPad上默认使YES。这个值决定了HTML5视频可以自动播放还是需要用户去启动播放@property(nonatomic) BOOL mediaPlaybackRequiresUserAction//这个值决定了从这个页面是否可以Air Play。 在iPhone和iPad上默认使YES.@property(nonatomic) BOOL mediaPlaybackAllowsAirPlay//设置主页,主页内容为baseURL链接内容.- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL//设置主页内容,MIME类型,编码的内容和基本的URL。data数据为主页内容- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL//运行JavaScript脚本- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script/* 返回运行脚本语言的结果。JavaScript的执行时间被限定在10秒钟,如果执行时间超过10秒,那么页面就停止执行这个脚本。JavaScript的执行或许能够阻塞主线程,所以当脚本执行的时候不允许用户影响页面的加载。JavaScript的内存分配被限制在10M,如果超出这个限制那么页面会发生异常。 *///加载资源- (void)loadRequest:(NSURLRequest *)request;

4.监听UIWebView的加载过程

 //开始发送请求(加载数据)时调用这个方法-(void)webViewDidStartLoad:(UIWebView *)webView;//请求完毕(加载数据完毕)时调⽤这个方法-(void)webViewDidFinishLoad:(UIWebView *)webView;//请求错误时调用这个方法-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;//UIWebView在发送请求之前,都会调⽤用这个⽅方法,如果返回NO,代表停⽌止加载 请求,返回YES,代表允许加载请求-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request   navigationType:(UIWebViewNavigationType)navigationType


下面将通过一个UIWebView开发一个简单的浏览器, 在这个浏览器中将实现这样几个功能:

1.如果输入以”file://”开头的地址将加载Bundle中的文件

2.如果输入以“http”开头的地址将加载网络资源

3.如果输入内容不符合上面两种情况将使用bing搜索此内容.

- (void)viewDidLoad {   [super viewDidLoad];    [self layoutUI];    }#pragma mark 界面布局-(void)layoutUI{    //添加地址栏    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64,ScreenWidth,44)];    _searchBar.delegate=self;    [self.view addSubview:_searchBar];        //添加浏览器控件    _webView=[[UIWebView alloc]initWithFrame:CGRectMake(0,_searchBar.bottom,ScreenWidth,ScreenHeight-64-44-44)];    _webView.dataDetectorTypes=UIDataDetectorTypeAll;//数据监测类型,例如内容中有邮件地址,点击之后可以打开邮件软件编写邮件.    _webView.delegate=self;    [self.view addSubview:_webView];        //添加下方工具栏    _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0,_webView.bottom,ScreenWidth, 44)];    UIButton *btnBack=[UIButton buttonWithType:UIButtonTypeCustom];    btnBack.bounds=CGRectMake(0, 0, 32, 32);    [btnBack setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];    [btnBack setImage:[UIImage imageNamed:@"back_disable.png"] forState:UIControlStateDisabled];    [btnBack addTarget:self action:@selector(webViewBack) forControlEvents:UIControlEventTouchUpInside];    _barButtonBack=[[UIBarButtonItem alloc]initWithCustomView:btnBack];    _barButtonBack.enabled=NO;        UIBarButtonItem *btnSpacing=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:                                UIBarButtonSystemItemFlexibleSpace target:nil action:nil];        UIButton *btnForward=[UIButton buttonWithType:UIButtonTypeCustom];    btnForward.bounds=CGRectMake(0, 0, 32, 32);    [btnForward setImage:[UIImage imageNamed:@"forward.png"] forState:UIControlStateNormal];    [btnForward setImage:[UIImage imageNamed:@"forward_disable.png"] forState:UIControlStateDisabled];    [btnForward addTarget:self action:@selector(webViewForward) forControlEvents:UIControlEventTouchUpInside];    _barButtonForward=[[UIBarButtonItem alloc]initWithCustomView:btnForward];    _barButtonForward.enabled=NO;        _toolbar.items=@[_barButtonBack,btnSpacing,_barButtonForward];    [self.view addSubview:_toolbar];}#pragma mark 设置前进后退按钮状态-(void)setBarButtonStatus{        if (_webView.canGoBack) {        _barButtonBack.enabled=YES;    }else{        _barButtonBack.enabled=NO;    }    if(_webView.canGoForward){        _barButtonForward.enabled=YES;    }else{        _barButtonForward.enabled=NO;    }    }//后退-(void)webViewBack{    [_webView goBack];}//前进-(void)webViewForward{    [_webView goForward];}#pragma mark 浏览器请求-(void)request:(NSString *)urlStr{        //1.创建url    NSURL *url;        //如果file://开头的字符串则加载bundle中的文件    if([urlStr hasPrefix:kFILEPROTOCOL]){                //取得文件名        NSRange range= [urlStr rangeOfString:kFILEPROTOCOL];        NSString *fileName=[urlStr substringFromIndex:range.length];        url=[[NSBundle mainBundle] URLForResource:fileName withExtension:nil];            }else if(urlStr.length>0){                //如果是http请求则直接打开网站        if ([urlStr hasPrefix:@"http"]) {                        url=[NSURL URLWithString:urlStr];                    }else{                        //如果不符合任何协议则进行搜索            urlStr=[NSString stringWithFormat:@"http://m.bing.com/search?q=%@",urlStr];        }        urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//url编码        url=[NSURL URLWithString:urlStr];            }        //2.创建请求    NSURLRequest *request=[NSURLRequest requestWithURL:url];        //3.加载请求页面    [_webView loadRequest:request];}#pragma mark - WebView 代理方法//开始加载-(void)webViewDidStartLoad:(UIWebView *)webView{        //显示网络请求加载    [UIApplication sharedApplication].networkActivityIndicatorVisible=true;}//加载完毕-(void)webViewDidFinishLoad:(UIWebView *)webView{        //隐藏网络请求加载图标    [UIApplication sharedApplication].networkActivityIndicatorVisible=false;    //设置按钮状态    [self setBarButtonStatus];        //加载完毕在对js进行操作.    self.title=[_webView stringByEvaluatingJavaScriptFromString:@"document.title"];}#pragma mark 加载失败-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{        NSLog(@"error detail:%@",error.localizedDescription);    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络连接发生错误!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];    [alert show];}#pragma mark - SearchBar 代理方法// 点击搜索按钮或回车/*  测试用例 http://www.apple.com   http://baidu.com/ file://iOS 7 Programming Cookbook.pdf iphone6 */-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{        [self request:_searchBar.text];    
效果图如下:

                  

其实UIWebView整个使用相当简单:创建URL->创建请求->加载请求,无论是加载本地文件还是Web内容都是这三个步骤。UIWebView内容加载事件同样是通过代理通知外界,常用的代理方法如开始加载、加载完成、加载出错等,这些方法通常可以帮助开发者更好的控制请求加载过程。

注意:UIWebView打开本地pdf、word文件依靠的并不是UIWebView自身解析,而是依靠MIME Type识别文件类型并调用对应应用打开。


加载文件, pdf,html

//加载文件- (void)loadFile{    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"关于.txt" withExtension:nil];    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];    [self.webView loadRequest:request];}//加载本地pdf,方式一-(void)loadPDF{        //设置需要展示的文件路径,并且取得mimeType类型    NSString * str=[[NSBundle mainBundle] pathForResource:@"iOS 7 Programming Cookbook.pdf" ofType:nil];    NSString * mimeType=[self getMimeType:str];        //调用方法加载数据    NSData * data=[NSData dataWithContentsOfFile:str];    [self.webView loadData:data MIMEType:mimeType textEncodingName:@"UTF-8" baseURL:nil];    }//以二进制数据的形式加载文件,方式二- (void)loadDataFile{     // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"iOS 7 Programming Cookbook.pdf" withExtension:nil];        NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];    // 服务器的响应对象,服务器接收到请求返回给客户端的    NSURLResponse *respnose = nil;        // 发送请求给服务器:url(http://服务器地址/资源路径),发送同步请求获取响应类型    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&respnose error:NULL];        NSLog(@"%@", respnose.MIMEType);        // 在iOS开发中,如果不是特殊要求,所有的文本编码都是用UTF8,先用UTF8解释接收到的二进制数据流    //调用方法加载数据    [self.webView loadData:data MIMEType:respnose.MIMEType textEncodingName:@"UTF8" baseURL:nil];}//获取MIMEType- (NSString *)getMimeType:(NSString * ) path{        //本地文件路径    NSURL * url=[NSURL fileURLWithPath:path];        //创建请求    NSURLRequest * request=[NSURLRequest requestWithURL:url];    NSURLResponse * response=nil;        //发送同步请求获取响应类型    [NSURLConnection sendSynchronousRequest:request returningResponse:(&response) error:nil];    return  response.MIMEType;}//加载html-(void)loadHtml{        //设置需要展示的文件路径,并且取得mimeType类型    NSString *str=[[NSBundle mainBundle] pathForResource:@"Example.html" ofType:nil];    NSString *mimeType=[self getMimeType:str];        //调用方法加载数据    NSData  *data=[NSData dataWithContentsOfFile:str];        NSString *htmlStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    [self.webView loadHTMLString:htmlStr baseURL:nil];}


0 0
原创粉丝点击