当前位置: 移动技术网 > 移动技术>移动开发>IOS > IOS之UIWebView的使用(基本知识)

IOS之UIWebView的使用(基本知识)

2019年07月24日  | 移动技术网移动技术  | 我要评论

刚接触ios开发1年多,现在对于混合式移动端开发越来越流行,因为开发成本上、速度上都比传统的app开发要好,混合式开发是传统模式与pc网页端相结合的模式。那么提到了 app的混合模式开发,在android开发中有webview作为混合模式开发的桥梁,当然在ios中也同样有一个 uiwebview 组件来作为混合模式开发的桥梁,那么下面就对uiwebview的一些基本知识详解一下。

一、uiwebview的基础使用

1、创建uiwebview:

cgrect bouds = [[uiscreen manscreen]applicationframe];
uiwebview* webview = [[uiwebview alloc]initwithframe:bounds];

2、设置属性:

webview.scalespagetofit = yes;//自动对页面进行缩放以适应屏幕
webview.detectsphonenumbers = yes;//自动检测网页上的电话号码,单击可以拨打

3、显示网页视图uiwebview:

[self.view addsubview:webview];

4、加载内容

nsurl* url = [nsurl urlwithstring:@"http://www.baidu.com"];//创建url
nsurlrequest* request = [nsurlrequest requestwithurl:url];//创建nsurlrequest
[webview loadrequest:request];//加载

也可以加载一个本地资源:

nsurl* url = [nsurl fileurlwithpath:filepath];//创建url
nsurlrequest* request = [nsurlrequest requestwithurl:url];//创建nsurlrequest
[webview loadrequest:request];//加载

uiwebview 还支持将一个nsstring对象作为源来加载。你可以为其提供一个基础url,来指导uiwebview对象如何跟随链接和加载远程资源:

[webview loadhtmlstring:myhtml baseurl:[nsurl urlwithstring:@"http://baidu.com"]];

5、导航

uiwebview类内部会管理浏览器的导航动作,通过goforward和goback方法你可以控制前进与后退动作:

[webview goback];
[webview goforward];
[webview reload];//重载
[webview stoploading];//取消载入内容

6、uiwebviewdelegate委托代理

uiwebview支持一组委托方法,这些方法将在特定时间得到通知。要使用这些方法,必须先设定webview的委托:

webview.delegate = self;

下面每个委托方法的第一个参数都是指向一个uiwebview的指针,因此你可以将一个委托用于多个网页视图。

-(bool)webview:(uiwebview*)webview shouldstartloadwithrequest:(nsurlrequest*) reuqest navigationtype: (uiwebviewnavigationtype)navigationtype;//当网页视图被指示载入内容而得到通知。应当返回yes,这样会进行加载。通过导航类型参数可以得到请求发起的原因,可以是以下任意值:
uiwebviewnavigationtypelinkclicked
uiwebviewnavigationtypeformsubmitted
uiwebviewnavigationtypebackforward
uiwebviewnavigationtypereload
uiwebviewnavigationtypeformresubmitted
uiwebviewnavigationtypeother

uiwebview控件加载网页的监听函数方法:

-(void)webviewdidstartload:(uiwebview*)webview ;//当网页视图已经开始加载一个请求后,得到通知。
-(void)webviewdidfinishload:(uiwebview*)webview ;//当网页视图结束加载一个请求之后,得到通知。
-(void)webview:(uiwebview*)webview didfailloadwitherror:(nserror*)error;//当在请求加载中发生错误时,得到通知。会提供一个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方法。(对应方法如第1条).

4、为webview添加背景图片:

approvalwebview.backgroundcolor=[uicolor clearcolor];
approvalwebview.opaque=no;//这句话很重要,webview是否是不透明的,no为透明 在webview下添加个imageview展示图片就可以了

5、获取webview页面内容信息:

nsstring *docstr=[webview stringbyevaluatingjavascriptfromstring:@"document.documentelement.textcontent"];//获取web页面内容信息,此处获取的是个json字符串
sbjsonparser *parserjson=[[[sbjsonparser alloc]init]autorelease];
nsdictionary *contentdic=[parserjson objectwithstring:docstr];//将json字符串转化为字典

6、 加载本地文件的方法:

//第一种方法:
nsstring* path = [[nsbundle mainbundle] pathforresource:name oftype:@"html" indirectory:@"mobile"];//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];
[uiwebview loadhtmlstring:htmlstring baseurl:[nsurl fileurlwithpath:[[nsbundle mainbundle] bundlepath]]];

7、将文件下载到本地址然后再用webview打开:

nsstring *resourcedocpath = [[nsstring alloc] initwithstring:[[[[nsbundle mainbundle] resourcepath] stringbydeletinglastpathcomponent] stringbyappendingpathcomponent:@"documents"]];
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:
@""
""
""
""
"%@"
"/pre>"
""
"",
astr];
[attachmentwebview loadhtmlstring:responsestr baseurl:[nsurl fileurlwithpath:[[nsbundle mainbundle] bundlepath]]];
return;
}

9、使用webview加载本地或网络文件整个流程:

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/"]]];
}

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];
}

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;
}
/************/
引用自苹果官方文档(displaying web content)

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在ios5.1之前的bug:在之前的工程中使用webview加载附件,webview支持doc,excel,ppt,pdf等格式,但这些附件必须先下载到本地然后在加载到webview上才可以显示, 当附件下载到本地之后刚刚开始加载到webview上时,此时退出附件页面会导致程序崩溃。会崩溃是由于webview控件内部没有把相关代理取消掉,所以导致退出之后程序崩溃。

webview在5.1上的bug:之前项目需求要webview可以左右活动,但在往webview上加载页面时导致页面加载不全,这个bug是由于webview本身的缓存所致。(还有待研究)

15、在使用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];
}
}
}

16、在uiwebview中使用flashscrollindicators

使用uiscrollview时,我们可以使用flashscrollindicators方法显示滚动标识然后消失,告知用户此页面可以滚动,后面还有 更多内容。uiwebview内部依赖于uiscrollview,但是其没有flashscrollindicators方法,但可以通过其他途径使用 此方法,如下所示。

for (id subview in [webview subviews])
{ if ([subview respondstoselector:@selector(flashscrollindicators)])
{
[subview flashscrollindicators];
}
}

上述代码片段可以到webviewdidfinishload回调中使用,加载完网页内容后flash显示滚动标识。

17、根据内容获取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;
}

总结:

首先 对ios开发中的uiwebview控件的基本使用进行初步的详解,提到了创建、设置属性、设置背景、怎么样加载网页内容等一系列的基础点,然后阐述使用uiwebview控件时常用用注意点,经常需要用到的地方,需要注意的地方,使得对开发ios app混合模式的桥梁---uiwebview控件更加的了解、熟悉。uiwebview既能够加载服务器提供的uri,又能够加载本地的资源文件,还能够加载服务器返回的网页界面代码,可想而知uiwebview是多么强大的一控件桥梁,以后在开发中使用到的地方会越来越多。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网