iOS中 UIWebView加载网络数据 技术分享

简介:

直奔核心:

[objc]  view plain  copy
  1. #import "TechnologyDetailViewController.h"  
  2. #define kScreenWidth [UIScreen mainScreen].bounds.size.width  
  3. #define kScreenHeight [UIScreen mainScreen].bounds.size.height  
  4. @interface TechnologyDetailViewController ()  
  5. @property (nonatomic,retain)UIWebView *webView;//显示详情页面  
  6. @end  

[objc]  view plain  copy
  1. @implementation TechnologyDetailViewController  
  2. - (void)dealloc  
  3. {  
  4.     self.webView = nil;  
  5.     self.ids = nil;  
  6.     [super dealloc];  
  7. }  
  8.   
  9. - (void)viewDidLoad {  
  10.     [super viewDidLoad];  
  11.     //设置背景  
  12.     self.view.backgroundColor = [UIColor yellowColor];  
  13.     //调用请求网络数据  
  14.     [self readDataFromNetWork];  
  15.     //    self.automaticallyAdjustsScrollViewInsets = NO;  
  16.     [self.view addSubview:self.webView];  
  17. }  


懒加载UIWebView

[objc]  view plain  copy
  1. //懒加载  
  2. - (UIWebView *)webView{  
  3.     if (!_webView) {  
  4.         self.webView = [[[UIWebView alloc]initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]autorelease];  
  5.         self.webView.backgroundColor = [UIColor orangeColor];  
  6.           
  7.     }  
  8.     return [[_webView retain ]autorelease];  
  9. }  


核心代码如下:

[objc]  view plain  copy
  1. //解析数据  
  2. - (void)readDataFromNetWork{  
  3.     NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html",self.ids];  
  4.     NSURL *url = [NSURL URLWithString:str];  
  5.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  6.     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  
  7.         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];  
  8.           
  9.           
  10.         NSString *body = dic[self.ids][@"body"];  
  11.         NSString * title = dic[self.ids][@"title"];  
  12.         NSString *digest = dic[self.ids][@"digest"];  
  13.         NSString *ptime = dic[self.ids][@"ptime"];  
  14.         NSString * source = dic[self.ids][@"source"];  
  15.         NSArray * img = dic[self.ids][@"img" ] ;  
  16.         //        NSLog(@"%@",img);  
  17.         if (img.count) {  
  18.             for (int i = 0; i < img.count; i ++) {  
  19.                   
  20.                   
  21.                 NSString *imgString = [NSString stringWithFormat:@"<p style=\"text-align:center\"><img src=\"%@\" /></p>",img[i][@"src"]];  
  22.                 NSLog(@"imString  = %@",imgString);  
  23.                   
  24.                 imgString = [imgString stringByReplacingOccurrencesOfString:@"<!--IMG#%d-->" withString:imgString];  
  25.                 body = [imgString stringByAppendingString:body];  
  26.                   
  27.                   
  28.             }  
  29.         }  
  30.         //        NSLog(@"body =  %@",body);  
  31.           
  32.         //借助第三方进行排版  
  33.         NSString *filePath = [[NSBundle mainBundle]pathForResource:@"topic_template" ofType:@"html"];  
  34.         NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];  
  35.           
  36.         htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__BODY__" withString:body];  
  37.         htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__TITLE__" withString:title];  
  38.         htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__AUTHOR__" withString:source];  
  39.         htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__DIGEST__" withString:digest];  
  40.         htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__TIME__" withString:ptime];  
  41.         htmlString = [htmlString stringByReplacingOccurrencesOfString:@"__PTIME__" withString:ptime];  
  42.         [self.webView loadHTMLString:htmlString baseURL:nil];  
  43.           
  44.           
  45.     }];  
  46.       
  47. }  


======================================================================================================

实在看不懂再看下demol例子:

UIWebView的loadRequest可以用来加载一个url地址,它需要一个NSURLRequest参数。我们定义一个方法用来加载url。在UIWebViewDemoViewController中定义下面方法:


[objc]  view plain  copy
  1. - (void)loadWebPageWithString:(NSString*)urlString  
  2. {  
  3.     NSURL *url =[NSURL URLWithString:urlString];  
  4.     NSLog(urlString);  
  5.     NSURLRequest *request =[NSURLRequest requestWithURL:url];  
  6.     [webView loadRequest:request];  
  7. }  


在界面上放置3个控件,一个textfield、一个button、一个uiwebview,布局如下:


在代码中定义相关的控件:webView用于展示网页、textField用于地址栏、activityIndicatorView用于加载的动画、buttonPress用于按钮的点击事件。


[objc]  view plain  copy
  1. @interface UIWebViewDemoViewController :UIViewController<UIWebViewDelegate> {     
  2.     IBOutlet UIWebView *webView;  
  3.     IBOutlet UITextField *textField;  
  4.     UIActivityIndicatorView *activityIndicatorView;  
  5.        
  6. }  
  7. - (IBAction)buttonPress:(id) sender;  
  8. - (void)loadWebPageWithString:(NSString*)urlString;  
  9. @end  


使用IB关联他们。

设置UIWebView,初始化UIActivityIndicatorView:

[objc]  view plain  copy
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     webView.scalesPageToFit =YES;  
  5.     webView.delegate =self;  
  6.     activityIndicatorView = [[UIActivityIndicatorView alloc]   
  7.                              initWithFrame : CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ;  
  8.     [activityIndicatorView setCenter: self.view.center] ;  
  9.     [activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleWhite] ;   
  10.     [self.view addSubview : activityIndicatorView] ;  
  11.     [self buttonPress:nil];  
  12.     // Do any additional setup after loading the view from its nib.  
  13. }  


UIWebView主要有下面几个委托方法:

1、- (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。
2、- (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。
3、- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。

我们可以将activityIndicatorView放置到前面两个委托方法中。

[objc]  view plain  copy
  1. - (void)webViewDidStartLoad:(UIWebView *)webView  
  2. {  
  3.     [activityIndicatorView startAnimating] ;  
  4. }  
  5. - (void)webViewDidFinishLoad:(UIWebView *)webView  
  6. {  
  7.     [activityIndicatorView stopAnimating];  
  8. }  


buttonPress方法很简单,调用我们开始定义好的loadWebPageWithString方法就行了:

[objc]  view plain  copy
  1. - (IBAction)buttonPress:(id) sender  
  2. {  
  3.     [textField resignFirstResponder];  
  4.     [self loadWebPageWithString:textField.text];  
  5.        
  6. }  


当请求页面出现错误的时候,我们给予提示:

[objc]  view plain  copy
  1. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  
  2. {  
  3.     UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription]  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil nil];  
  4.     [alterview show];  
  5.     [alterview release];  
  6. }  


总结:本文通过实现一个简单的浏览器,说明了uiwebview的方法和属性,相信通过这个例子,应该明白uiwebview的使用了。

有疑问可通过新浪微博私信给我:http://weibo.com/hanjunqiang
相关文章
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
1759 4
|
机器学习/深度学习 算法 调度
14种智能算法优化BP神经网络(14种方法)实现数据预测分类研究(Matlab代码实现)
14种智能算法优化BP神经网络(14种方法)实现数据预测分类研究(Matlab代码实现)
811 0
|
机器学习/深度学习 数据采集 传感器
【故障诊断】基于matlab BP神经网络电机数据特征提取与故障诊断研究(Matlab代码实现)
【故障诊断】基于matlab BP神经网络电机数据特征提取与故障诊断研究(Matlab代码实现)
384 0
|
Python
LBA-ECO CD-32 通量塔网络数据汇编,巴西亚马逊:1999-2006,V2
该数据集汇集了1999年至2006年间巴西亚马逊地区九座观测塔的碳和能量通量、气象、辐射等多类数据,涵盖小时至月度时间步长。作为第二版汇编,数据经过协调与质量控制,扩展了第一版内容,并新增生态系统呼吸等相关计算数据,支持综合研究与模型合成。数据以36个制表符分隔文本文件形式提供,配套PDF说明文件,适用于生态与气候研究。引用来源为Restrepo-Coupe等人(2021)。
605 1
|
数据采集 存储 算法
MyEMS 开源能源管理系统:基于 4G 无线传感网络的能源数据闭环管理方案
MyEMS 是开源能源管理领域的标杆解决方案,采用 Python、Django 与 React 技术栈,具备模块化架构与跨平台兼容性。系统涵盖能源数据治理、设备管理、工单流转与智能控制四大核心功能,结合高精度 4G 无线计量仪表,实现高效数据采集与边缘计算。方案部署灵活、安全性高,助力企业实现能源数字化与碳减排目标。
549 0
|
安全 Linux 虚拟化
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
746 3
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
|
机器学习/深度学习 人工智能 算法
【基于TTNRBO优化DBN回归预测】基于瞬态三角牛顿-拉夫逊优化算法(TTNRBO)优化深度信念网络(DBN)数据回归预测研究(Matlab代码实现)
【基于TTNRBO优化DBN回归预测】基于瞬态三角牛顿-拉夫逊优化算法(TTNRBO)优化深度信念网络(DBN)数据回归预测研究(Matlab代码实现)
473 0
|
机器学习/深度学习 数据采集 运维
改进的遗传算法优化的BP神经网络用于电厂数据的异常检测和故障诊断
改进的遗传算法优化的BP神经网络用于电厂数据的异常检测和故障诊断
|
存储 监控 算法
基于 Python 跳表算法的局域网网络监控软件动态数据索引优化策略研究
局域网网络监控软件需高效处理终端行为数据,跳表作为一种基于概率平衡的动态数据结构,具备高效的插入、删除与查询性能(平均时间复杂度为O(log n)),适用于高频数据写入和随机查询场景。本文深入解析跳表原理,探讨其在局域网监控中的适配性,并提供基于Python的完整实现方案,优化终端会话管理,提升系统响应性能。
585 4
|
开发者
鸿蒙仓颉语言开发教程:网络请求和数据解析
本文介绍了在仓颉开发语言中实现网络请求的方法,以购物应用的分类列表为例,详细讲解了从权限配置、发起请求到数据解析的全过程。通过示例代码,帮助开发者快速掌握如何在网络请求中处理数据并展示到页面上,减少开发中的摸索成本。
鸿蒙仓颉语言开发教程:网络请求和数据解析