[IOS]UIWebView实现保存页面和读取服务器端json数据

简介:

如何通过viewView保存访问过的页面?和如何获取并解析服务器端发送过来的json数据?通过一个简单的Demo来学习一下吧!

操作步骤:

1.创建SingleViewApplication应用,新建VIewController,并在xib试图中添加WebView,继承webview的Delegate协议。

2.将ViewController类遵循UIWebViewDelegate和NSURLConnectionDataDelegate协议,并且实现协议中的方法。

ViewController.h:

#import <UIKit/UIKit.h>  @interface ViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate> @property (retain, nonatomic) IBOutlet UIWebView *webview; @property (retain, nonatomic) UIAlertView * alert; @property (retain, nonatomic) IBOutlet UITextField *searchText; - (IBAction)searchClick:(id)sender;   @property (retain, nonatomic) IBOutlet UILabel *label; @property (retain, nonatomic) NSURLConnection * connection; @property (retain, nonatomic) NSMutableData * data; @end

VIewController.m:

#import "ViewController.h"

@interfaceViewController ()

@end

@implementation ViewController

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    //请求网络页面

//    NSURL * url = [NSURL URLWithString:@"http://www.taobao.com"];   //一定要加http://

//    NSURLRequest * request = [NSURLRequest requestWithURL:url];

//    [self.webview loadRequest:request];

//    

//    

//    //html加载本地网页

//    NSString * str = [[NSBundle mainBundle] pathForResource:@"百度图片全球最大中文图片库" ofType:@"html"];

//    str = [NSString stringWithContentsOfFile:str encoding:NSUTF8StringEncoding error:nil];

//    NSLog(@"%@",str);

//    [self.webview loadHTMLString:str baseURL:[[NSBundle mainBundle]bundleURL]];

//    

     

    self.label.text =@"正在请求数据";

    //step1:请求地址

    //保存页面

    //NSString * urlString = @"http://www.baidu.com";

   //访问服务器获取json数据

    NSString * urlString =@"http://www.weather.com.cn/data/cityinfo/101020100.html";

    NSURL * url = [NSURLURLWithString:urlString];

    //step2:实例化一个request

    NSURLRequest * request = [NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:30.0];

    //step3:创建链接

    self.connection = [[NSURLConnectionalloc]initWithRequest:request delegate:self];

    if(self.connection)

    {

        NSLog(@"创建链接成功");

    }else{

        NSLog(@"创建链接失败");

    }

    [url release];

    [urlString release];

    

}


- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)dealloc {

    [_webview release];

    [_searchTextrelease];

    [_label release];

    [super dealloc];

}

//获取数据

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    //接受一个服务端回话,再次一般初始化接受数据的对象

    //NSLog(@"返回数据类型%@",[response ]);

    //NSLog(@"返回数据编码%@",[response text]);

    NSMutableData * data = [[NSMutableDataalloc]init];

    self.data = data;

    [data release];

}

//不断的获取数据

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    //接受返回数据,这个方法可能会被调用多次,因此将多次返回数据加起来

    NSInteger datalength = [datalength];

    NSLog(@"返回数据量:%d",datalength);

    [self.dataappendData:data];

}

//获取文件地址

-(NSString *)dataFilePath:(NSString*)fileName

{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *document=[pathsobjectAtIndex:0];

    return [documentstringByAppendingPathComponent:fileName];

}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

//    //连接结束

    NSLog(@"%d",[self.datalength]);

    self.label.text =@"请求结束";

    //可以下载图片

    //[self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES];

    

    NSString * mystr = [[NSStringalloc]initWithData:self.dataencoding:NSUTF8StringEncoding];

    [mystr writeToFile:[selfdataFilePath:@"百度图片全球最大中文图片库.html"] atomically:YES encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"最后的结果%@",mystr);

    [mystr release];

//    NSDictionary *weather = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers  error:nil];

//    NSLog(@"%@",weather);

//    [weather writeToFile:[self dataFilePath:@"weather.plist"] atomically:YES];

}


-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    self.label.text =@"连接失败";

}

- (IBAction)searchClick:(id)sender {

}

@end


结果:

2013-08-27 16:09:18.821 WebViewDemo[673:c07] 创建链接成功

2013-08-27 16:09:19.161 WebViewDemo[673:c07] 返回数据量:153

2013-08-27 16:09:19.161 WebViewDemo[673:c07] 153

2013-08-27 16:09:19.193 WebViewDemo[673:c07] 最后的结果{"weatherinfo":{"city":"上海","cityid":"101020100","temp1":"32","temp2":"27","weather":"多云","img1":"d1.gif","img2":"n1.gif","ptime":"11:00"}}



==================== 迂者 丁小未 CSDN博客专栏=================

MyBlog:http://blog.csdn.net/dingxiaowei2013             MyQQ:1213250243

Unity QQ群:858550         cocos2dx QQ群:280818155

====================== 相互学习,共同进步 ===================

转载请注明出处:http://blog.csdn.net/dingxiaowei2013/article/details/10399799

欢迎关注我的微博: http://weibo.com/u/2590571922












相关文章
|
5月前
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:
|
5月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
5月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
6月前
|
JSON 缓存 自然语言处理
多语言实时数据微店商品详情API:技术实现与JSON数据解析指南
通过以上技术实现与解析指南,开发者可高效构建支持多语言的实时商品详情系统,满足全球化电商场景需求。
|
5月前
|
JSON 中间件 Java
【GoGin】(3)Gin的数据渲染和中间件的使用:数据渲染、返回JSON、浅.JSON()源码、中间件、Next()方法
我们在正常注册中间件时,会打断原有的运行流程,但是你可以在中间件函数内部添加Next()方法,这样可以让原有的运行流程继续执行,当原有的运行流程结束后再回来执行中间件内部的内容。​ c.Writer.WriteHeaderNow()还会写入文本流中。可以看到使用next后,正常执行流程中并没有获得到中间件设置的值。接口还提供了一个可以修改ContentType的方法。判断了传入的状态码是否符合正确的状态码,并返回。在内部封装时,只是标注了不同的render类型。再看一下其他返回的类型;
290 3
|
5月前
|
JSON Java Go
【GoGin】(2)数据解析和绑定:结构体分析,包括JSON解析、form解析、URL解析,区分绑定的Bind方法
bind或bindXXX函数(后文中我们统一都叫bind函数)的作用就是将,以方便后续业务逻辑的处理。
398 3
|
6月前
|
JSON API 数据安全/隐私保护
Python采集淘宝评论API接口及JSON数据返回全流程指南
Python采集淘宝评论API接口及JSON数据返回全流程指南
|
6月前
|
JSON 自然语言处理 监控
淘宝关键词搜索与商品详情API接口(JSON数据返回)
通过商品ID(num_iid)获取商品全量信息,包括SKU规格、库存、促销活动、卖家信息、详情页HTML等。
|
6月前
|
JSON 自然语言处理 API
多语言实时数据淘宝商品评论API:技术实现与JSON数据解析指南
淘宝商品评论多语言实时采集需结合官方API与后处理技术实现。建议优先通过地域站点适配获取本地化评论,辅以机器翻译完成多语言转换。在合规前提下,企业可构建多语言评论数据库,支撑全球化市场分析与产品优化。
|
6月前
|
机器学习/深度学习 JSON API
干货,淘宝拍立淘按图搜索,淘宝API(json数据返回)
淘宝拍立淘按图搜索API接口基于深度学习与计算机视觉技术,通过解析用户上传的商品图片,在淘宝商品库中实现毫秒级相似商品匹配,并以JSON格式返回商品标题、图片链接、价格、销量、相似度评分等详细信息。