[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












相关文章
|
2天前
|
XML JSON API
转Android上基于JSON的数据交互应用
转Android上基于JSON的数据交互应用
|
10天前
|
JSON JavaScript Java
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
22 0
|
12天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;city&quot;: &quot;New York&quot;}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
17 1
|
12天前
|
JSON 数据格式 Python
Python处理JSON数据
【4月更文挑战第30天】该内容介绍了Python处理JSON数据的三个方法:1)使用`json.loads()`尝试解析字符串以验证其是否为有效JSON,通过捕获`JSONDecodeError`异常判断有效性;2)通过`json.dumps()`的`indent`参数格式化输出JSON数据,使其更易读;3)处理JSON中的日期,利用`dateutil`库将日期转换为字符串进行序列化和反序列化。
23 4
|
15天前
|
存储 JSON 数据处理
|
16天前
|
JSON 数据可视化 定位技术
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
19 0
|
25天前
|
JSON JavaScript 数据格式
vue展示json数据,vue-json-viewer的使用
vue展示json数据,vue-json-viewer的使用
31 0
|
1月前
|
JSON 前端开发 Java
Json格式数据解析
Json格式数据解析
|
4月前
|
JSON PHP 数据格式
|
2月前
|
存储 JSON Apache
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
在最新发布的阿里云数据库 SelectDB 的内核 Apache Doris 2.1 新版本中,我们引入了全新的数据类型 Variant,对半结构化数据分析能力进行了全面增强。无需提前在表结构中定义具体的列,彻底改变了 Doris 过去基于 String、JSONB 等行存类型的存储和查询方式。
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%