ios学习:NSURLConnection 和 Json数据解析

来源:互联网 发布:淘宝对中国经济的贡献 编辑:程序博客网 时间:2024/05/18 01:17

复制代码
 1 #import <UIKit/UIKit.h> 2  3 @interface TWFXViewController : UIViewController 4  5 @property (retain,nonatomic) NSMutableData *weatherData; 6  7 @property (retain, nonatomic) IBOutlet UILabel *outlet_weatherInfo; 8  9 - (IBAction)btnClick_getWeather:(UIButton *)sender;10 11 @end
复制代码

 

复制代码
  1 //  2 //  TWFXViewController.m  3 //  DemoConnection  4 //  5 //  Created by Lion User on 13-1-24.  6 //  Copyright (c) 2013年 Lion User. All rights reserved.  7 //  8   9 #import "TWFXViewController.h" 10  11 @interface TWFXViewController () 12  13 @end 14  15 @implementation TWFXViewController 16  17 - (void)viewDidLoad 18 { 19     [super viewDidLoad]; 20     // Do any additional setup after loading the view, typically from a nib. 21      22     //label多行显示 23     self.outlet_weatherInfo.numberOfLines = 0; 24      25 } 26  27 - (void)didReceiveMemoryWarning 28 { 29     [super didReceiveMemoryWarning]; 30     // Dispose of any resources that can be recreated. 31 } 32  33 - (IBAction)btnClick_getWeather:(UIButton *)sender { 34      35     NSString *strURL = @"http://m.weather.com.cn/data/101180601.html"; 36      37     //创建URL 38     NSURL *url = [[NSURL alloc] initWithString:strURL]; 39      40     //根据URL创建 NSURLRequest 请求 41     NSURLRequest *request = [[NSURLRequest alloc] 42                            initWithURL:url 43                            cachePolicy:NSURLRequestReloadIgnoringCacheData 44                            timeoutInterval:60]; 45      46     //参数cachePolicy表示缓存策略,枚举类型,值有以下几种: 47     // 48 //    enum 49 //    { 50 //        NSURLRequestUseProtocolCachePolicy  = 0  NSURLRequest默认的cache policy,使用Protocol协议定义。是最能保持一致性的协议。 51 //        NSURLRequestReloadIgnoringCacheData = 1  忽略缓存直接从原始地址下载 = NSURLRequestReloadIgnoringCacheData 52 //        NSURLRequestReturnCacheDataElseLoad = 2  只有在cache中不存在data时才从原始地址下载 53 //        NSURLRequestReturnCacheDataDontLoad = 3  只使用cache数据,如果不存在cache,请求失败;用于没有建立网络连接离线模式; 54 //        NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4,  忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似。 55 //        NSURLRequestReloadRevalidatingCacheData = 5  验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据。 56 //    }; 57 //    typedef NSUInteger NSURLRequestCachePolicy; 58  59  60  61     //创建连接,该消息一发送下载会立即开始 62     //在代理(得了噶个)收到connectionDidFinishLoading:或者didFailWithError:消息之前 可以通过给连接发送一个cancel:消息来中断下载 63     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 64      65     [url release]; 66     [request release]; 67      68     if (connection) 69     { 70         //此时才创建NSMutableData 的实例,是否已晚?下载已经异步开始了 71         if (!_weatherData) { 72              73             self.weatherData = [NSMutableData data];     74         } 75     } 76     else 77     {         78         NSLog(@"创建网络连接失败!"); 79     } 80  81 } 82  83  84 //当服务器提供了足够客户程序创建NSURLResponse对象的信息时,代理对象会收到 85 //一个connection:didReceiveResponse:消息,在消息内可以检查NSURLResponse 86 //对象和确定数据的预期长途,mime类型,文件名以及其他服务器提供的元信息 87  88 //要注意,一个简单的连接也可能会收到多个connection:didReceiveResponse:消息 89 //当服务器连接重置或者一些罕见的原因(比如多组mime文档),代理都会收到该消息 90 //这时候应该重置进度指示,丢弃之前接收的数据 91  92 //反正当收到该信息就表示下载开始了(或者是重新开始了),把之前的数据清空即可 93 -(void)connection:connection didReceiveResponse:(NSURLResponse *)response 94 { 95     [self.weatherData setLength:0]; 96      97    //int expectedLength = [response expectedContentLength];  该方法可以获取将要下载的信息的大小(字节长度) 98 } 99 100 101 //当下载开始的时候,每当有数据接收,代理会定期收到connection:didReceiveData:消息102 //代理应当在实现中储存新接收的数据,下面的例子既是如此103 //在下面的方法实现中,可以加入一个进度指示器,提示用户下载进度104 -(void)connection:connection didReceiveData:(NSData *)data105 {106     [self.weatherData appendData:data];107     108     // [data length]; 表示每次接收的信息的大小(字节长度)109 }110 111 112 //当下载的过程中有错误发生的时候,代理会收到一个connection:didFailWithError消息113 //消息参数里面的NSError对象提供了具体的错误细节,它也能提供在用户信息字典里面失败的114 //url请求(使用NSErrorFailingURLStringKey)115 116 //当代理接收到连接的connection:didFailWithError消息后,该连接不会再收到任何消息,所以应该release掉117 118 -(void)connection:connection didFailWithError:(NSError *)error119 {120     [connection release];121     122   //  [_weatherData release];123     NSLog(@"Connection failed! Error - %@ %@",124           [error localizedDescription],125           [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);126 }127 128 129 //最后,如果连接请求成功的下载,代理会接收connectionDidFinishLoading:消息130 //该消息之后代理不会再收到其他任何的消息了,在消息的实现中,应该释放掉连接131 - (void)connectionDidFinishLoading: (NSURLConnection *) connection132 {133     //do something with the data134 135     NSLog(@"succeeded %d byte receive",[self.weatherData length]);136     [connection release];137     138     //调用函数解析下载到的json格式的数据139     [self readJsonData];140 }141 142 143 //解析下载到的json格式的数据144 - (void)readJsonData145 {146    // NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)147     //和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。148     149     NSError *error;150     NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:self.weatherData151                                                                options:NSJSONReadingMutableContainers152                                                                  error:&error];153     154     //option参数说明.155 //    enum {156 //        NSJSONReadingMutableContainers = (1UL << 0),   //返回的容器是可变类型的(Array和Dictionary)157 //        NSJSONReadingMutableLeaves = (1UL << 1),     //返回的叶子NSString是可变类型的;158 //        NSJSONReadingAllowFragments = (1UL << 2)   //允许顶层的界面不是NSArray或NSDictionary;159 //    };160 //    typedef NSUInteger NSJSONReadingOptions;161     162     NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];163     164     self.outlet_weatherInfo.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];165 166 }167 168 -(void) dealloc169 {170     [_weatherData release];171     [_outlet_weatherInfo release];172     [super dealloc];173 }174 175 176 @end