一、UIWebView的基础使用
- (void)viewDidLoad {
[super viewDidLoad];
// 1、创建UIWebView:
CGRect bouds = [UIScreen mainScreen].bounds;
UIWebView* webView = [[UIWebView alloc]initWithFrame:bouds];
// 2、加载在线资源http内容
NSURL* url = [NSURL URLWithString:@"http://www.baidu.com"];//创建URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建
[webView loadRequest:request];//加载
// 2、 加载本地文件的方法:
/** * //第一种方法: NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];//mobile是根目录,name是文件名称,html是文件类型 [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //加载本地文件 //第二种方法: NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"]; NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; [webView loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; */
// 3、导航
// UIWebView类内部会管理浏览器的导航动作,通过goForward和goBack方法你可以控制前进与后退动作:
[webView goBack];
[webView goForward];
// 4、UIWebViewDelegate委托代理
webView.delegate = self;
// 5、显示网页视图UIWebView:
[self.view addSubview:webView];
}
# pragma mark - UIWebView 的代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;//当网页视图被指示载入内容而得到通知。应当返回YES,这样会进行加载
- (void)webViewDidStartLoad:(UIWebView *)webView { //当网页视图已经开始加载一个请求后,得到通知。
// [webView stopLoading];//取消载入内容
}
- (void)webViewDidFinishLoad:(UIWebView *)webView;//当网页视图结束加载一个请求之后,得到通知。
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
// [webView reload];//重载
}//当在请求加载中发生错误时,得到通知。会提供一个NSSError对象,以标识所发生错误类型。
以上是IOS中UIWebView的基础使用要点详解,接下来一些UIWebView的常用注意点算是比较细节的部分。
二、IOS中UIWebView常用注意点:
1、与UIWebView进行交互,调用web页面中的需要传参的函数时,参数需要带单引号,或者双引号(双引号要进行转义在转义字符前加\),传递json字符串时不需要加单引号或双引号:
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")", jsDocPathStr];
[webView stringByEvaluatingJavaScriptFromString:sendJsStr];
}
2、在该代理方法中判断与webView的交互,可通过html里定义的协议实现:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType;
3、只有在webView加载完毕之后在能够调用对应页面中的js方法。
4、为webView添加背景图片:
webView.backgroundColor=[UIColor clearColor];
//这句话很重要,webView是否是不透明的,no为透明 在webView下添加个imageView展示图片就可以了
webView.opaque=NO;
5、获取webView页面内容信息:
NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
//获取web页面内容信息,此处获取的是个son字符串
SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *contentDic=[parserJson objectWithString:docStr];
//将json字符串转化为字典
6、将文件下载到本地址然后再用webView打开(打开HTML5):
NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"];
NSString *resourceDocPath = [[NSString alloc] initWithString:path];
self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@",docType]];
NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]];
[attachmentData writeToFile:filePath atomically:YES];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[attachmentWebView loadRequest:requestObj];
//删除指定目录下的文件
NSFileManager *magngerDoc=[NSFileManager defaultManager];
[magngerDoc removeItemAtPath:filePath error:nil];
8、处理webView展示txt文档乱码问题:
if ([theType isEqualToString:@".txt"]) {
//txt分带编码和不带编码两种,带编码的如UTF-8格式txt,不带编码的如ANSI格式txt
//不带的,可以依次尝试GBK和GB18030编码
NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr)
{
//用GBK进行编码
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr)
{
//用GBK编码不行,再用GB18030编码
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
//通过html语言进行排版
NSString* responseStr = [NSString stringWithFormat:
@"%@",aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
}
9、使用webView加载本地或网络文件整个流程:
9.1、Loading a local PDF file into the web view
- (void)viewDidLoad {
[super viewDidLoad];
//从本地加载
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf"
textEncodingName:@"utf-8" baseURL:nil];
}
//从网络加载
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]]];
}
9.2、The web-view delegate managing network loading
- (void)webViewDidStartLoad:(UIWebView *)webView
{
// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// finished loading, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:@"An error occurred:%@",error.localizedDescription];
[self.myWebView loadHTMLString:errorString baseURL:nil];
}
9.3、Stopping a load request when the web view is to disappear
- (void)viewWillDisappear:(BOOL)animated {
if ( [self.myWebView loading] ) {
[self.myWebView stopLoading];
}
self.myWebView.delegate = nil; // disconnect the delegate as the webview is hidden
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
10、查找webView中的scrollview:
- (void) addScrollViewListener {
UIScrollView* currentScrollView;
for (UIView* subView in self.webView.subviews) {
if ([subView isKindOfClass:[UIScrollView class]]) {
currentScrollView = (UIScrollView*)subView;
currentScrollView.delegate = self;
}
}
11、去掉webView的阴影,做成类似scrollView:
- (void)clearBackgroundWithColor:(UIColor*)color {
// 去掉webview的阴影
self.backgroundColor = color;
for (UIView* subView in [self subviews])
{
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
}
12、取消长按webView上的链接弹出actionSheet的问题:
-(void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];
}
13、取消webView上的超级链接加载问题:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType==UIWebViewNavigationTypeLinkClicked) {
return NO;
} else {
return YES;
}
}
14、在使用webView进行新浪微博分享时,webView会自动保存登陆的cookie导致项目中的分享模块有些问题,删除 webView的cookie的方法:
-(void)deleteCookieForDominPathStr:(NSString *)thePath
{
//删除本地cookie,thePath为cookie路径通过打印cookie可知道其路径
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
if([[cookie domain] isEqualToString:thePath]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
}
15、在UIWebView中使用flashScrollIndicators
使用UIScrollView时,我们可以使用flashScrollIndicators方法显示滚动标识然后消失,告知用户此页面可以滚动,后面还有更多内容。UIWebView内部依赖于UIScrollView,但是其没有flashScrollIndicators方法,但可以通过其他途径使用此方法,如下所示。
for (id subView in [webView subviews]){
if ([subView respondsToSelector:@selector(flashScrollIndicators)]){
[subView flashScrollIndicators];
}
}
上述代码片段可以到webViewDidFinishLoad回调中使用,加载完网页内容后flash显示滚动标识。
16、根据内容获取UIWebView的高度:
有时候需要根据不同的内容调整UIWebView的高度,以使UIWebView刚好装下所有内容,不用拖动,后面也不会留白。有两种方式可根据加载内容获取UIWebView的合适高度,但都需要在网页内容加载完成后才可以,即需要在webViewDidFinishLoad回调中使用
①.使用sizeThatFits方法。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
frame.size.height = 1;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
}
sizeThatFits方法有个问题,如果当前UIView的大小比刚好合适的大小还大,则返回当前的大小,不会返回最合适的大小值,所以使用sizeThatFits前,先将UIWebView的高度设为最小,即1,然后再使用sizeThatFits就会返回刚好合适的大小。
②、使用JavaScript
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
frame.size.height = [fitHeight floatValue];
webView.frame = frame;
}