iOS中 UIWebView加载网络数据 技术分享
直奔核心:
#import "TechnologyDetailViewController.h" #define kScreenWidth [UIScreen mainScreen].bounds.size.width #define kScreenHeight [UIScreen mainScreen].bounds.size.height @interface TechnologyDetailViewController () @property (nonatomic,retain)UIWebView *webView;//显示详情页面 @end
@implementation TechnologyDetailViewController - (void)dealloc { self.webView = nil; self.ids = nil; [super dealloc]; } - (void)viewDidLoad { [super viewDidLoad]; //设置背景 self.view.backgroundColor = [UIColor yellowColor]; //调用请求网络数据 [self readDataFromNetWork]; // self.automaticallyAdjustsScrollViewInsets = NO; [self.view addSubview:self.webView]; }
懒加载UIWebView
//懒加载 - (UIWebView *)webView{ if (!_webView) { self.webView = [[[UIWebView alloc]initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]autorelease]; self.webView.backgroundColor = [UIColor orangeColor]; } return [[_webView retain ]autorelease]; }
核心代码如下:
//解析数据 - (void)readDataFromNetWork{ NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html",self.ids]; NSURL *url = [NSURL URLWithString:str]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *body = dic[self.ids][@"body"]; NSString * title = dic[self.ids][@"title"]; NSString *digest = dic[self.ids][@"digest"]; NSString *ptime = dic[self.ids][@"ptime"]; NSString * source = dic[self.ids][@"source"]; NSArray * img = dic[self.ids][@"img" ] ; // NSLog(@"%@",img); if (img.count) { for (int i = 0; i < img.count; i ++) { NSString *imgString = [NSString stringWithFormat:@"<p style=\"text-align:center\"><img src=\"%@\" /></p>",img[i][@"src"]]; NSLog(@"imString = %@",imgString); imgString = [imgString stringByReplacingOccurrencesOfString:@"<!--IMG#%d-->" withString:imgString]; body = [imgString stringByAppendingString:body]; } } // NSLog(@"body = %@",body); //借助第三方进行排版 NSString *filePath = [[NSBundle mainBundle]pathForResource:@"topic_template" ofType:@"html"]; NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__BODY__" withString:body]; htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__TITLE__" withString:title]; htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__AUTHOR__" withString:source]; htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__DIGEST__" withString:digest]; htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__TIME__" withString:ptime]; htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__PTIME__" withString:ptime]; [self.webView loadHTMLString:htmlString baseURL:nil]; }]; }
======================================================================================================
实在看不懂再看下demol例子:
UIWebView的loadRequest可以用来加载一个url地址,它需要一个NSURLRequest参数。我们定义一个方法用来加载url。在UIWebViewDemoViewController中定义下面方法:
- (void)loadWebPageWithString:(NSString*)urlString { NSURL *url =[NSURL URLWithString:urlString]; NSLog(urlString); NSURLRequest *request =[NSURLRequest requestWithURL:url]; [webView loadRequest:request]; }
在界面上放置3个控件,一个textfield、一个button、一个uiwebview,布局如下:
在代码中定义相关的控件:webView用于展示网页、textField用于地址栏、activityIndicatorView用于加载的动画、buttonPress用于按钮的点击事件。
@interface UIWebViewDemoViewController :UIViewController<UIWebViewDelegate> { IBOutlet UIWebView *webView; IBOutlet UITextField *textField; UIActivityIndicatorView *activityIndicatorView; } - (IBAction)buttonPress:(id) sender; - (void)loadWebPageWithString:(NSString*)urlString; @end
使用IB关联他们。
设置UIWebView,初始化UIActivityIndicatorView:
- (void)viewDidLoad { [super viewDidLoad]; webView.scalesPageToFit =YES; webView.delegate =self; activityIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame : CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ; [activityIndicatorView setCenter: self.view.center] ; [activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleWhite] ; [self.view addSubview : activityIndicatorView] ; [self buttonPress:nil]; // Do any additional setup after loading the view from its nib. }
UIWebView主要有下面几个委托方法:
1、- (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。
2、- (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。
3、- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。
我们可以将activityIndicatorView放置到前面两个委托方法中。
- (void)webViewDidStartLoad:(UIWebView *)webView { [activityIndicatorView startAnimating] ; } - (void)webViewDidFinishLoad:(UIWebView *)webView { [activityIndicatorView stopAnimating]; }
buttonPress方法很简单,调用我们开始定义好的loadWebPageWithString方法就行了:
- (IBAction)buttonPress:(id) sender { [textField resignFirstResponder]; [self loadWebPageWithString:textField.text]; }
当请求页面出现错误的时候,我们给予提示:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alterview show]; [alterview release]; }
有疑问可通过新浪微博私信给我:http://weibo.com/hanjunqiang
iOS中 UIWebView加载网络数据 技术分享的更多相关文章
- 关于IOS中UIWebView 加载HTML内容
NSString *strContent=[info objectForKey:@"newContent"]; { NSArray *paths = NSSearchPathFor ...
- iOS开发-UIWebView加载本地和网络数据
UIWebView是内置的浏览器控件,可以用它来浏览网页.打开文档,关于浏览网页榜样可以参考UC,手机必备浏览器,至于文档浏览的手机很多图书阅读软件,UIWebView是一个混合体,具体的功能控件内置 ...
- UITableView加载网络数据的优化
UITableView加载网络数据的优化 效果 源码 https://github.com/YouXianMing/Animations // // TableViewLoadDataControll ...
- iOS中wkwebview加载本地html的要点
项目中有些页面,我采用了html页面开发,然后用wkwebview加载的设计.在加载过程中遇见了一些问题,在这里进行一些记载和讨论.如有不同意见欢迎进行评论沟通. 问题时候这样的: 在webview的 ...
- android122 zhihuibeijing 新闻中心NewsCenterPager加载网络数据实现
新闻中心NewsCenterPager.java package com.itheima.zhbj52.base.impl; import java.util.ArrayList; import an ...
- Flink 中定时加载外部数据
社区中有好几个同学问过这样的场景: flink 任务中,source 进来的数据,需要连接数据库里面的字段,再做后面的处理 这里假设一个 ETL 的场景,输入数据包含两个字段 “type, useri ...
- Android之ListView&Json加载网络数据
使用到的主要内容: 1.Json 解析网络数据 2.异步任务加载图片和数据 3.ListView 的内存空间优化(ConvertView)和运行时间优化(ViewHolder) 4.ListView ...
- IOS中图片加载的一些注意点
图片的加载: [UIImage imageNamed:@"home"] //加载 png图片 在ios中获取一张图片只需要写图片名即可 不需要写后缀 默认都是加载.png的图片 但 ...
- iOS中webView加载URL需要处理特殊字符
今天在项目中遇到webView加载URL时,因为URL中有特殊字符,导致页面无法加载,而且在- (BOOL)webView:(UIWebView )webView shouldStartLoadWit ...
随机推荐
- Linux允许、禁止ping包
默认情况下Linux系统允许ping,但是在某些情况下为了安全起见,我们都把服务器设置为禁ping 临时允许ping命令可使用命令: echo 0 >/proc/sys/net/ipv4/ic ...
- sb error
width: $("#StudentManagement").parent().width(), height: $("#StudentManagement") ...
- TCP/IP学习笔记__mbuf
Socket发送和接收数据都是写入和读取mbuf(存储器缓存)来完成的.下面着重介绍下Sendto函数与mbuf的关系: 以UDP协议为例: 1.UDP的输出执行过程: UDP的输出执行过程 2.协议 ...
- spring boot+mybaits+mysql+generato(逆向工程)+前后台数据交互
如按照我博客上没有弄出来 请在下面留言 我好修改 谢谢 小弟使用的是Eclipse 首先下载STS插件 help--->Elipse Marketplace--->find搜索栏里面搜索S ...
- word_count
网址:http://www.wimoney.xin/HTML/upload.html 在我的网站上干不起,不晓得是不是文件保存的问题,也可能是windows和linux有些地方有差异,妈个鸡,我得再去 ...
- li标签中list-style-image如何居中
使用list-style-image设置了一个列表项的小图标时,一直不能让图标居中的显示. 解决办法是:使用ul li的backgrou-image(背景图片)来设置. 代码如下: ul li{ he ...
- jQuery – AJAX get() 和 post() 方法
jQuery get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据. HTTP 请求:GET vs. POST 两种在客户端和服务器端进行请求-响应的常用方 ...
- Do a web framework ourselves
step 1: from wsgiref.simple_server import make_server def application(environ, start_response): star ...
- 王家林人工智能AI课程大纲和电子书 - 老师微信13928463918
**3980元团购原价19800元的AI课程,团购请加王家林老师微信13928463918. 基于王家林老师独创的人工智能"项目情景投射"学习法,任何IT人员皆可在无需数学和Pyt ...
- Useful command for Docker
Copy file from Container to Host: docker cp <containerId>:/file/path/within/container /host/pa ...