使用UIWebView加载网页

1、使用UIWebView加载网页

运行XCode 4.3,新建一个Single View Application,命名为WebViewDemo。


2、加载WebView

在ViewController.h添加WebView成员变量和在ViewController.m添加实现

[cpp] view plaincopyprint?
  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface ViewController : UIViewController  
  4. {  
  5.     UIWebView *webView;  
  6. }  
  7. @end  
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
UIWebView *webView;
}
@end
[cpp] view plaincopyprint?
  1. ViewController.m  
ViewController.m
[cpp] view plaincopyprint?
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];  
  5.     NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];  
  6.     [self.view addSubview: webView];  
  7.     [webView loadRequest:request];  
  8. }  
- (void)viewDidLoad
{
[super viewDidLoad];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
[self.view addSubview: webView];
[webView loadRequest:request];
}
运行,这样百度网页就打开了


手机的网络环境是实时变化的,网络慢的时候,怎么提示用户网页正在打开呢?在网页打开出错的时候怎么提示用户呢?这时候我们就需要知道网页什么时候打开的,

什么时候加载完成,什么时候出错了。那么我们需要实现这个<UIWebViewDelegate>协议

3、实现协议,在ViewController.h修改如下:

[cpp] view plaincopyprint?
  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface ViewController : UIViewController<UIWebViewDelegate>  
  4. {  
  5.     UIWebView *webView;  
  6. }  
  7. @end  
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIWebViewDelegate>
{
UIWebView *webView;
}
@end

按住control+command+向上键,切换到ViewController.m文件,这是我们在文件中打入- (void) webView,就能看到如下实现方法:



UIWebView中几个重要的函数
1.- (void )webViewDidStartLoad:(UIWebView  *)webView   网页开始加载的时候调用
2.- (void )webViewDidFinishLoad:(UIWebView  *)webView  网页加载完成的时候调用
3.- (void)webView:(UIWebView *)webView  didFailLoadWithError:(NSError *)error 网页加载错误的时候调用

4、实现这三个方法,加入NSLog。

先在viewDidLoad 的webView实例化下面加上

    [webView setDelegate:self];设置代理。这样上面的三个方法才能得到回调。

三个方法实现如下:

[cpp] view plaincopyprint?
  1. <SPAN style="FONT-FAMILY: Arial, Verdana, sans-serif; COLOR: #333333">- (void) webViewDidStartLoad:(UIWebView *)webView  
  2. {  
  3.     NSLog(@"webViewDidStartLoad");  
  4. }  
  5. - (void) webViewDidFinishLoad:(UIWebView *)webView  
  6. {  
  7.     NSLog(@"webViewDidFinishLoad");  
  8. }  
  9. - (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  
  10. {  
  11.     NSLog(@"didFailLoadWithError:%@", error);  
  12. }  
  13. </SPAN>  
- (void) webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"webViewDidStartLoad");
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"webViewDidFinishLoad");
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"didFailLoadWithError:%@", error);
}
运行打印:

2012-06-23 15:20:29.728 WebViewDemo[1001:f803] webViewDidStartLoad

2012-06-23 15:20:29.991 WebViewDemo[1001:f803] webViewDidFinishLoad

那我们试试error情况,把wifi关掉,运行打印结果:

2012-06-23 15:23:58.939 WebViewDemo[1087:f803] webViewDidStartLoad

2012-06-23 15:23:59.016 WebViewDemo[1087:f803] webViewDidFinishLoad

请求结果不变,为什么关掉网络还成功了呢?缓存?我换163.com试试,这是真正的结果出来了:

2012-06-23 15:24:41.131 WebViewDemo[1134:f803] webViewDidStartLoad

2012-06-23 15:24:41.149 WebViewDemo[1134:f803] didFailLoadWithError:Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x6b41660 {NSErrorFailingURLStringKey=http://www.163.com/, NSErrorFailingURLKey=http://www.163.com/, NSLocalizedDescription=The Internet connection appears to be offline., NSUnderlyingError=0x6eae690 "The Internet connection appears to be offline."}

连接错误了,调用了 didFailLoadWithError。

5、加载等待界面

为了给用户更直观的界面效果,我们加上等待的loading界面试试

在webViewDidStartLoad加入等待

[cpp] view plaincopyprint?
  1. <STRONG>- (void) webViewDidStartLoad:(UIWebView *)webView  
  2. {  
  3.     //创建UIActivityIndicatorView背底半透明View        
  4.     UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];    
  5.     [view setTag:108];    
  6.     [view setBackgroundColor:[UIColor blackColor]];    
  7.     [view setAlpha:0.5];    
  8.     [self.view addSubview:view];    
  9.       
  10.     activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];    
  11.     [activityIndicator setCenter:view.center];    
  12.     [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];    
  13.     [view addSubview:activityIndicator];    
  14.   
  15.     [activityIndicator startAnimating];  
  16.    </STRONG>  
- (void) webViewDidStartLoad:(UIWebView *)webView
{
//创建UIActivityIndicatorView背底半透明View     
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];  
[view setTag:108];  
[view setBackgroundColor:[UIColor blackColor]];  
[view setAlpha:0.5];  
[self.view addSubview:view];  
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];  
[activityIndicator setCenter:view.center];  
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];  
[view addSubview:activityIndicator];  
[activityIndicator startAnimating];

加载完成或失败时,去掉loading效果

[cpp] view plaincopyprint?
  1. <STRONG>- (void) webViewDidFinishLoad:(UIWebView *)webView  
  2. {  
  3.     [activityIndicator stopAnimating];  
  4.     UIView *view = (UIView*)[self.view viewWithTag:108];  
  5.     [view removeFromSuperview];  
  6.     NSLog(@"webViewDidFinishLoad");  
  7.   
  8. }  
  9. - (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  
  10. {  
  11.     [activityIndicator stopAnimating];  
  12.     UIView *view = (UIView*)[self.view viewWithTag:108];  
  13.     [view removeFromSuperview];  
  14.     </STRONG>  
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:108];
[view removeFromSuperview];
NSLog(@"webViewDidFinishLoad");
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:108];
[view removeFromSuperview];
运行效果:


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388287.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

corba的兴衰_数据科学薪酬的兴衰

corba的兴衰意见 (Opinion) 目录 (Table of Contents) Introduction 介绍 Salary and Growth 薪资与增长 Summary 摘要 介绍 (Introduction) In the past five years, data science salary cumulative growth has varied between 12% in the United States, according to Glass…

10 个深恶痛绝的 Java 异常。。

异常是 Java 程序中经常遇到的问题&#xff0c;我想每一个 Java 程序员都讨厌异常&#xff0c;一 个异常就是一个 BUG&#xff0c;就要花很多时间来定位异常问题。 什么是异常及异常的分类请看这篇文章&#xff1a;一张图搞清楚 Java 异常机制。今天&#xff0c;栈长来列一下 J…

如何实施成功的数据清理流程

干净的数据是发现和洞察力的基础。 如果数据很脏&#xff0c;您的团队为分析&#xff0c;培养和可视化数据而付出的巨大努力完全是在浪费时间。 当然&#xff0c;肮脏的数据并不是新的。 它早在计算机变得普及之前就困扰着决策。 现在&#xff0c;计算机技术已普及到日常生活中…

通才与专家_那么您准备聘请数据科学家了吗? 通才还是专家?

通才与专家Throughout my 10-year career, I have seen people often spend their time and energy in passionate debates about what data science can deliver, and what data scientists do or do not do. I submit that these are the wrong questions to focus on when y…

ubuntu opengl 安装

安装相应的库&#xff1a; sudo apt-get install build-essential libgl1-mesa-dev sudo apt-get install freeglut3-dev sudo apt-get install libglew-dev libsdl2-dev libsdl2-image-dev libglm-dev libfreetype6-dev 实例&#xff1a; #include "GL/glut.h" void…

分享一病毒源代码,破坏MBR,危险!!仅供学习参考,勿运行(vc++2010已编译通过)

我在编译的时候&#xff0c;杀毒软件提示病毒并将其拦截&#xff0c;所以会导致编译不成功。 1>D:\c工程\windows\windows\MBR病毒.cpp : fatal error C1083: 无法打开编译器中间文件:“C:\Users\lenovo\AppData\Local\Temp\_CL_953b34fein”: Permission denied 1> 1>…

数据科学家 数据工程师_数据科学家实际上赚了多少钱?

数据科学家 数据工程师目录 (Table of Contents) Introduction 介绍 Junior Data Scientist 初级数据科学家 Mid-Level Data Scientist 中级数据科学家 Senior Data Scientist 资深数据科学家 Additional Compensation 额外补偿 Summary 摘要 介绍 (Introduction) The lucrativ…

spotify歌曲下载_使用Spotify数据预测哪些“ Novidades da semana”歌曲会成为热门歌曲

spotify歌曲下载TL; DR (TL;DR) Spotify is my favorite digital music service and I’m very passionate about the potential to extract meaningful insights from data. Therefore, I decided to do this article to consolidate my knowledge of some classification mod…

(第三周)周报

此作业要求https://edu.cnblogs.com/campus/nenu/2018fall/homework/2143 1.本周PSP 总计&#xff1a;1422 min 2.本周进度条 (1)代码累积折线图 (2)博文字数累积折线图 4.PSP饼状图 转载于:https://www.cnblogs.com/gongylx/p/9761852.html

功能测试代码python_如何使您的Python代码更具功能性

功能测试代码pythonFunctional programming has been getting more and more popular in recent years. Not only is it perfectly suited for tasks like data analysis and machine learning. It’s also a powerful way to make code easier to test and maintain.近年来&am…

layou split 属性

layou split&#xff1a;true - 显示侧分栏 转载于:https://www.cnblogs.com/jasonlai2016/p/9764450.html

C#Word转Html的类

C#Word转Html的类/**//******************************************************************** created: 2007/11/02 created: 2:11:2007 23:13 filename: D:C#程序练习WordToChmWordToHtml.cs file path: D:C#程序练习WordToChm file bas…

分库分表的几种常见形式以及可能遇到的难题

前言 在谈论数据库架构和数据库优化的时候&#xff0c;我们经常会听到“分库分表”、“分片”、“Sharding”…这样的关键词。让人感到高兴的是&#xff0c;这些朋友所服务的公司业务量正在&#xff08;或者即将面临&#xff09;高速增长&#xff0c;技术方面也面临着一些挑战。…

线性回归和将线拟合到数据

Linear Regression is the Supervised Machine Learning Algorithm that predicts continuous value outputs. In Linear Regression we generally follow three steps to predict the output.线性回归是一种监督机器学习算法&#xff0c;可预测连续值输出。 在线性回归中&…

小米盒子4 拆解图解_我希望当我开始学习R时会得到的盒子图解指南

小米盒子4 拆解图解Customizing a graph to transform it into a beautiful figure in R isn’t alchemy. Nonetheless, it took me a lot of time (and frustration) to figure out how to make these plots informative and publication-quality. Rather than hoarding this …

蓝牙一段一段_不用担心,它在那里存在了一段时间

蓝牙一段一段You’re sitting in a classroom. You look around and see your friends writing something down. It seems they are taking the exam, and they know all the answers (even Johnny who, how to say it… wasn’t the brilliant one). You realize that your ex…

普通话测试系统_普通话

普通话测试系统Traduzido/adaptado do original por Vincius Barqueiro a partir do texto original “Writing Alt Text for Data Visualization”, escrito por Amy Cesal e publicado no blog Nightingale.Traduzido / adaptado由 VinciusBarqueiro 提供原始 文本“为数据可…

美国队长3:内战_隐藏的宝石:寻找美国最好的秘密线索

美国队长3:内战There are plenty of reasons why one would want to find solitude in the wilderness, from the therapeutic effects of being immersed in nature, to not wanting to contribute to trail degradation and soil erosion on busier trails.人们有很多理由想要…

Java入门第三季——Java中的集合框架(中):MapHashMap

1 package com.imooc.collection;2 3 import java.util.HashSet;4 import java.util.Set;5 6 /**7 * 学生类8 * author Administrator9 * 10 */ 11 public class Student { 12 13 public String id; 14 15 public String name; 16 17 public Set<…

动漫数据推荐系统

Simple, TfidfVectorizer and CountVectorizer recommendation system for beginner.简单的TfidfVectorizer和CountVectorizer推荐系统&#xff0c;适用于初学者。 目标 (The Goal) Recommendation system is widely use in many industries to suggest items to customers. F…