iOS获取天气情况的总结

最近在整理各种关于天气获取的方法,现在将学习到的东西进行总结。其实,天气获取的实例,主要分为两个部分,第一个部分就是通过网络获取到数据,第二个 部分是获取到数据后的分析处理。处理之后就是你自己开发的程序的问题,如何显示得更加的漂亮。


第一个部分关于数据获取。

            通过网络获取数据的方法,有两种,一种是通过NSRUL,NSURLREQUEST,NSURLCONNECTION的方法获取。另一种方法是直接通过NSData的initContentwithURLdataWithContentsOfURL的方法。


描述如下:

方法1:


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

    NSURL *url = [NSURL URLWithString:googleURL];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    NSURLConnection *connection = [[NSURLConnection allocinitWithRequest:request delegate:self];

    [connection release];

    [request release];


委托的处理方法:

    

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

outString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];

NSLog(@"%@", outString);

}


-(void) connection:(NSURLConnection *)connection

  didFailWithError: (NSError *)error {

    

}


- (void) connectionDidFinishLoading: (NSURLConnection*) connection {

    

}



方法2:


#define kWeatherServiceURLStr @"http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?heCityName="


    NSString *RequestUrlStr = [NSString stringWithFormat:@"%@%@",kWeatherServiceURLStr,[[ipCityLocation citySimpleName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];


    NSLog(@"request = %@", RequestUrlStr);


    NSData * ReponseData = [NSData dataWithContentsOfURL:[NSURL URLWithString:RequestUrlStr]];



第二部分为获取数据后的,数据分析,数据部分通常来讲也有两种方法,第一种是获取到的数据为JSON,第二种方法获取到的数据为XML。


方法1:获取到的数据为JSON。


iOS5之前并没有提供比较好的JSON类库,但是ios5之后就提供了一种公共的方法NSJSONSerialization,而为了保证ios5之前的方法也可以使用,需要使用的第三方库有SBJson和TouchJSON。不过好像SBJson用的人比较多。具体方法实例如下:


TouchJSON:

         //获取API接口

  1. NSURL*url=[NSURLURLWithString:@"http://m.weather.com.cn/data/101010100.html"];
  2. //定义一个NSError对象,用于捕获错误信息
  3. NSError*error;
  4. //
  5. NSString*jsonString=[NSString   stringWithContentsOfURL:url  encoding:NSUTF8StringEncoding  error:&error];

  6. //将解析得到的内容存放字典中,编码格式UTF8,防止取值时候发生乱码
  7. NSDictionary*rootDic=[[CJSONDeserializerdeserializer]deserialize:[jsonStringdataUsingEncoding:NSUTF8StringEncoding]error:&error];
  8. //因为返回的Json文件有两层,去第二层类容放到字典中去0
  9. NSDictionary*weatherInfo=[rootDicobjectForKey:@"weatherinfo"];
  10. //取值打印
  11. NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);

SBJson:

  1. NSURL*url=[NSURLURLWithString:@"http://m.weather.com.cn/data/101180701.html"];
  2. NSError*error=nil;
  3. NSString*jsonString=[NSStringstringWithContentsOfURL:urlencoding:NSUTF8StringEncodingerror:&error];
  4. SBJsonParser*parser=[[SBJsonParseralloc]init];
  5. NSDictionary*rootDic=[parserobjectWithString:jsonStringerror:&error];
  6. NSDictionary*weatherInfo=[rootDicobjectForKey:@"weatherinfo"];
  7. NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);

iOS类库提供的标准做法:

  1. NSError*error;
  2. //加载一个NSURL对象
  3. NSURLRequest*request=[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
  4. //将请求的url数据放到NSData对象中
  5. NSData*response=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil];
  6. //iOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
  7. NSDictionary*weatherDic=[NSJSONSerializationJSONObjectWithData:responseoptions:NSJSONReadingMutableLeaveserror:&error];
  8. //weatherDic字典中存放的数据也是字典型,从它里面通过键值取值
  9. NSDictionary*weatherInfo=[weatherDicobjectForKey:@"weatherinfo"];
  10. NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);
  11. //打印出weatherInfo字典所存储数据
  12. NSLog(@"weatherInfo字典里面的内容是--->%@",[weatherInfodescription]);

注意一个问题就是解析出现崩溃的问题,解决方法如下:

4.运行结果(如果想知道每次字符串和字典间取值情况,只需NSLog打印输出就行):




1、取值时发生应用程序崩溃,获取值不正确

有时我们从字典中获取了这样的数据,感觉比较郁闷,并未显示中文,这种情况是我们把数据放到字典中,编码方式是UTF8,取值打印出来的时候就成中文了



在解析出来数据后我想这样取值,

NSDictionary*weatherInfo = [rootDicobjectForKey:@"weatherinfo"];

NSArray*weatherArray = [rootDicobjectForKey:@"weatherinfo"];

for(NSDictionary*dicinweatherArray) {

NSLog(@"----->%@",dic);

}

打印出来的dic数据是这样的


这是我们json文件的第二层数据取出放到了一个数组中,然后定义了一个字典对象在数组中遍历取出存放的数据,于是就想用

NSLog(@"----->%@",[dicobjectForKey:@"city"]);来取出city的值,但是应用程序崩溃


出现这种情况是因为在对解析出数据存值和取值发生问题,说明这种方式是取值是不正确的;

方法2,采用XML的解析方法。

xmlParser = [[NSXMLParser alloc] initWithData:weatherReponseData];

[xmlParser setDelegate:self];

[xmlParser setShouldProcessNamespaces:NO];

[xmlParser setShouldReportNamespacePrefixes:NO];

[xmlParser setShouldResolveExternalEntities:NO];


// 启动解析命令


- (void)startParse{

// 开始解析

[xmlParser parse];

}


// 设定委托方法

#pragma mark NSXMLParserDelegate

#pragma mark xml parser delegate

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{



NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];

string = [string stringByTrimmingCharactersInSet:whitespace];

if (![string isEqualToString:@"\n"]) {

[xmlWeatherStringArray addObject:string];

}

}


- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{

NSLog(@"%@", [parseError description]);

}


- (void)parserDidEndDocument:(NSXMLParser *)parser{

[self outputParseInfo];

//取出xml中数据后提取信息 

[self splitXmlWeatherInfo];

}



    


   



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值