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

UIWebView相关

2013-10-29 10:58 357 查看
1.只有使用loadRequest:加载网页,才能对之后的链接操作做goBack,goForward操作,即canGoBack,canGoForward才有可能返回YES.

使用loadHTMLString,loadData都不可以.

并且在load之后通过stringByEvaluatingJavaScriptFromString对网页增加的内容,在

NSString* outerHTML = [iWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];//document.documentElement.innerHTML

中都不会出现。

可以使用loadRequestl加载本地文件,但还不能解决其中的网络图片问题:

NSURLRequest* request=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:@“/Users/../1.html”]];

[iWebView loadRequest:request];

使用loadRequest,NSURLRequest 的代理获得进度?

2.把要请求的地址直接交于UIWebView loadRequest,它在请求时,也会把这个地址回调到shouldStartLoadWithRequest代理方法中,询问是否由浏览器自己请求.

把内容直接设置给UIWebView,之后在请求内容中的图片时不会调用shouldStartLoadWithRequest。

另外内容中有些需要加Referer头的图片,不能过通过UIWebView设置这个头。即 shouldStartLoadWithRequest中,request即使是NSMutableURLRequest类型,设置request的头,请求后这些头不会被带。

3.goBack也会请求页面,也会回调代理方法.

4. NSURLErrorDomain error -999.

This error may occur if an another request is made before the previous request of WebView is completed...

I worked around this by ignoring this error and letting the webview continue to load.

5.双击一个图片链接不会调用到shouldStartLoadWithRequest

判断点击到的是否是图片,可设置特殊的url,或判断当前点击的tag,使用window.pageYOffset,window.pageXOffset,window.outerWidth,document.elementFromPoint等。

例如 NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];,

js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).getAttribute('_src')", pt.x, pt.y];

获取自定义属性的值时,用getAttribute。

7.设置背景色后,如下:iWebView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];

当内容很长时,会占用很大内存,这说明它会根据ContentSize平铺,而不是Bounds;

使用iWebView.backgroundColor=[UIColor blackColor];则不会占用这么大的内存。

8.webView_.opaque = NO;//设置webView最上面的内容的背景透明

webView_.backgroundColor=[UIColor clearColor];//设置其中的scrollView透明

使用图片背景的方案是:在iWebView的下面同级加一层UIImageView, iWebView.backgroundColor=[UIColor clearColor];,当内容拖动到头或尾时,会透出iWebView下面的背景。

如果要让内容的背景也透明,再设置不透明属性为NO:webView.opaque = NO;

利用这些属性可以实现在顶部或底部拖动时,展现刷新提示效果;

8.在顶部和底部时,禁用拖动回弹:

for (id subview in iWebView.subviews)

{

if ([[subview class] isSubclassOfClass: [UIScrollView class]])

{

((UIScrollView *)subview).bounces = NO;

}

}

禁止UIWebView的bounces

http://www.flyblog.info/catprogramming/303.html

底部灰色阴影其实是个imageview,hidden就行了,不影响任何正常操作:

for(UIView *v in [[[iWebView subviews] objectAtIndex:0] subviews])

{

if([v isKindOfClass:[UIImageView class]])

{

v.hidden = YES;

}

}

或者

for (UIView *shadowView in [webView_.scrollView subviews])

{

if ([shadowView isKindOfClass:[UIImageView class]])

{

shadowView.hidden = YES;

}

}

或者

// remove shadow view when drag web view
for (UIView *subView in [webView_ subviews]) {
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView *shadowView in [subView subviews]) {
if ([shadowView isKindOfClass:[UIImageView class]]) {
shadowView.hidden = YES;
}
}
}
}


让网页自适应屏幕

webview.scalesPageToFit = YES;

在网页中写下面的js代码,也可以实现bounces = NO的功能

document.onload = function(){
document.ontouchmove = function(e){ e.preventDefault(); }
}


9.由此服务端日志记录可知,iphone端safiri及UIWebView的图片缓存是没有的。每次访问都需要从服务端重新下载图片

http://tangqiaoboy.blog.163.com/blog/static/11611425820118672051584/

cachePolicy:NSURLRequestUseProtocolCachePolicy???

对同一个设置为本地src的img,UIWebView总是缓存其内容,重建UIWebView依旧。只能重新启动软件。在图片地址后加上@"?t=%ld",time(NULL) ,

localPath=[localPath stringByAppendingFormat:@"?t=%ld",time(NULL) ];,再loadHtml,可解决问题。原理是在图片后面加了一个随机数,让浏览器不再读取缓存。
http://stackoverflow.com/questions/11516278/how-to-clear-cache-for-my-uiwebviews-loadhtmlstring http://www.techques.com/question/1-11516278/How-to-clear-cache-for-my-UIWebView's-loadHtmlString
10.UIWebView的stringByEvaluatingJavaScriptFromString只能在主线程里面被调用,如果恰好这个js执行时间比较长,就会造成程序卡死。

跟 Mac OS X 比较起来,iPhone 上 UIWebView 的公开 API 实在少上许多.

http://spring-studio.net/?p=265

11.UIWebView之获取所点位置图片URL

http://www.cocoachina.com/newbie/basic/2011/1031/3439.html

12.显示本地图片

NSString* logoPath=[FileUtil getDocumentsFullPath:@"logol.png"];

或 NSString* logoPath=[[NSBundle mainBundle] pathForResource:@"logol" ofType:@"png"];

NSString* local_image_path=[NSString stringWithFormat:@"file://%@",pathForResource];

NSString* script=[NSString stringWithFormat:@"changeImgSrc(\"%@\");",local_image_path];

[iWebView stringByEvaluatingJavaScriptFromString:script];

例如:baseUrl设置为:file:///Users/gzty1/Library/Application Support/iPhone Simulator/4.2/Applications/85B80321-2BBC-4FFA-9D3D-2DD1B/myapp.app/

image.src 设置为file:///Users/gzty1/Library/Application Support/iPhone Simulator/4.2/Applications/85B80321-2BBC-4FFA-9D3D-2DD1B/myapp.app/logo.png

注意:file后面是冒号加3个斜杠。

//显示安装包中的图片,baseURL使用[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]

[webView_ loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

13. 禁用长按UIWebView时放大镜及选择功能:

//通过js调用

- (void)webViewDidFinishLoad:(UIWebView*)webView

{

// Disable user selection

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];

// Disable callout,禁止长按链接弹出菜单,默认带有打开,拷贝,取消3个菜单项。

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];

//修改整个页面的字体大小

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '150%';"];

//修改点击链接时的高亮背景色

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTapHighlightColor='#FF0000';"];

}

//嵌入在页面中

//修改点击链接时的高亮背景色

<a href=http://yourlink.com/ style = "-webkit-tap-highlight-color:rgba(0,0,0,0);">

webkit webApp 开发技术要点总结
http://www.cnblogs.com/pifoo/archive/2011/05/28/webkit-webapp.ht
14.禁用UIWebView中双击和手势缩放页面,但测试结果是缩小了一半,确实不影响双击了,但不缩小时仍然响应双击上下滚动。

http://blog.163.com/alex_kame/blog/static/14546748201171263254740/

http://learnthemobileweb.com/2009/07/mobile-meta-tags/

15.用UIWebView显示gif

UIImage* tempImage=[UIImage imageWithData:data];

CGRect rect = CGRectZero;

rect.size = tempImage.size;

iWebView = [[UIWebView alloc] initWithFrame:rect];

[self addSubview:iWebView];

[iWebView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

iWebView.userInteractionEnabled=NO;

iWebView.opaque = NO;

iWebView.backgroundColor=[UIColor clearColor];

16. UIWebView处理authentication方法

参考 http://www.cocoachina.com/newbie/basic/2011/1123/3583.html
17.elementFromPoint() under iOS 5

http://www.icab.de/blog/2011/10/17/elementfrompoint-under-ios-5/

NSString* js = [NSString stringWithFormat:@"elementFromViewportPoint(%f, %f).tagName", pt.x, pt.y];

//private

function viewportCoordinateToDocumentCoordinate(x,y)

{

var coord = new Object();

coord.x = x + window.pageXOffset;

coord.y = y + window.pageYOffset;

return coord;

}

//private

function elementFromPointIsUsingViewPortCoordinates()

{

if (window.pageYOffset > 0)

{

// page scrolled down

return (window.document.elementFromPoint(0, window.pageYOffset + window.innerHeight -1) == null);

}

else if (window.pageXOffset > 0)

{

// page scrolled to the right

return (window.document.elementFromPoint(window.pageXOffset + window.innerWidth -1, 0) == null);

}

return false; // no scrolling, don't care

}

//public

function elementFromViewportPoint(x,y)

{

if (elementFromPointIsUsingViewPortCoordinates())

{

return window.document.elementFromPoint(x,y);

}

else

{

var coord = viewportCoordinateToDocumentCoordinate(x,y);

return window.document.elementFromPoint(coord.x,coord.y);

}

}

内容高度 : int contentHeight=[[webView_ stringByEvaluatingJavaScriptFromString:@"document.body.clientHeight"] intValue];

18.滚动到顶部

[webView_ stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];

19.在UIGestureRecognizer的响应函数中调用打开一个有输入框的页面,UIGestureRecognizer的响应中后续会让webview再次获得焦点,从而使键盘隐藏。

这样把事件放到shouldStartLoadWithRequest中来曲线解决问题。

20. webapp是css+html来描述的,没办法简单的用name@2x 解决问题,继续求教中

iphone4图片问题
http://aralbalkan.com/3331
在head中添加 <meta name="viewport" content="width=device-width, initial-scale=0.5, minimum-scale=0.5, maximum-scale=yes" />

<meta align="center" name="viewport" content="width=480; initial-scale=0.5; maximum-scale=0.5; user-scalable=no;"/>

也可以控制页面的缩放,但并不统一。

为视网膜显示屏优化网页上的图片

(via:http://xuui.net/ui-design/retinal-display-to-optimize-the-image-the-on-the-the-page.html).

在网页中,pixel 与 point 比值称为 device-pixel-ratio,普通设备都是1,iPhone 4是2,有些Android机型是1.5。

Detecting taps and events on UIWebView – The right way
http://mithin.in/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way
21.对UIWebView中的数据的网络请求,js操作,一定要放到webViewDidFinishLoad调用之后,否则很可能出现找不到标签的异常问题。!!

html模板中,把要替换的内容放在div中,不要放在p中,否则不保证样式正常显示。

22.在顶部向下拖动一段距离的事件

UIScrollView* scrollView = [webView_.subviews objectAtIndex:0];

if (scrollView && [scrollView isKindOfClass:[UIScrollView class]])

{

scrollView.delegate = self;

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate

{

CGPoint offset = scrollView.contentOffset;

NSLog(@"%@",NSStringFromCGPoint(offset));

if(offset.y<=-60.0)

{

[super onNavigationBackPressed];

}

}

23.

webView_=[[UIWebView alloc] initWithFrame:webRect];

webView_.delegate=self;

webView_.dataDetectorTypes = UIDataDetectorTypeNone;

webView_.opaque = NO; //背景透明

webView_.backgroundColor=[UIColor whiteColor];

[self.view addSubview:webView_];

self.view.backgroundColor=[UIColor blackColor];

//隐藏灰影

for(UIView *v in [[[webView_ subviews] objectAtIndex:0] subviews])

{

if([v isKindOfClass:[UIImageView class]])

{

v.hidden = YES;

}

}

//拖动事件

UIScrollView* scrollView = [webView_.subviews objectAtIndex:0];

if (scrollView && [scrollView isKindOfClass:[UIScrollView class]])

{

scrollView.delegate = self;

}

//圆角

[[webView_ layer] setCornerRadius:10];

[webView_ setClipsToBounds:YES];

[[webView_ layer] setBorderColor:[[UIColor blackColor] CGColor]];

//[[webView_ layer] setBorderWidth:2.75];

[(UIScrollView *)[[webview subviews] objectAtIndex:0] setBounces:NO];

24. 取得选中的内容

给UIWebView增加类别

- (NSString *)selectedText {

return [self stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];

}

25.iphone web框架

iUi http://code.google.com/p/iui/ 它是一个javascript和css库,用于在网页中模拟iphone的外观和感觉。虽然是专为iphone设计的UI,但在android上90%以上的功能是完全可以使用的,因为android和iphone一样,都是基于webkit浏览器的系统。

iUI框架:用Eclipse开发iOS Web应用程序
http://www.61ic.com/Mobile/iPhone/201203/41389.html
26.[iOS]给UIWebView头尾插入自定义View
http://blog.cnbang.net/tech/1784/
示例代码下载:
https://github.com/bang590/iOSPlayground/tree/master/TWebview
11个基本的移动Web编程工具
http://developer.51cto.com/art/201107/273822.htm
27.iOS 5中safari带来的新特性
http://www.qianduan.net/ios-5-brings-new-features-in-safari.html
28.HTML5 Showcase
http://www.apple.com/html5/showcase/typography/
29.不用UIWebView辅助排版的困难

表情图片混在文字中;

图片后加载,大小不一,使列表跳动;

预知图片尺寸,或固定尺寸;

30.点击UIImageView打开键盘,未测试
http://android-zhang.iteye.com/blog/1758562
31.手机版网页的table优化处理 (未使用过)
http://www.liubiao4123.com/table_mobile.html
32.在UIWebView上追加菜单项
http://blog.csdn.net/andyweike/article/details/6061096
33.关于UIWebView的那些事儿(更新中)
http://www.lanou3g.com/blog/post-163.html
34.使用base64
http://iphoneincubator.com/blog/windows-views/display-images-in-uiwebview 未使用过

35.UIWebView 离线浏览 之图片显示

假如我们要获取的网页代码为

<html>

......bla....bla....bla

<img src="http://www.abc.com/test.png"/>

.....bla...bla....bla.

</html>

首先 解析上面img的link,然后存取图片到Documents目录,假设为 $full_doc_dir/test.png

然后把代码中的img的link改为:

<img src="file://$full_doc_dir/test.png"/>

注意上面代码中的 file:// 少了这个则图片显示不出来。

最后把此网页代码存到Documents目录下为html或txt即可,譬如存为mypage

app启动时自动读取mypage的内容显示到UIWebView即可。

测试时,最好在真机进行。因为每次模拟器重装都会动态改变当前app的目录。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: