第一个部分关于数据获取。
通过网络获取数据的方法,有两种,一种是通过NSRUL,NSURLREQUEST,NSURLCONNECTION的方法获取。另一种方法是直接通过NSData的initContentwithURL或dataWithContentsOfURL的方法。
描述如下:
方法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 = [[NSURLConnectionalloc] initWithRequest:request delegate:self];
[connection release];
[request release];
委托的处理方法:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
outString = [[NSStringalloc] 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 = [NSStringstringWithFormat:@"%@%@",kWeatherServiceURLStr,[[ipCityLocationcitySimpleName] 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接口
- NSURL*url=[NSURLURLWithString:@"http://m.weather.com.cn/data/101010100.html"];
- //定义一个NSError对象,用于捕获错误信息
- NSError*error;
- //
- NSString*jsonString=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
-
- //将解析得到的内容存放字典中,编码格式UTF8,防止取值时候发生乱码
- NSDictionary*rootDic=[[CJSONDeserializerdeserializer]deserialize:[jsonStringdataUsingEncoding:NSUTF8StringEncoding]error:&error];
- //因为返回的Json文件有两层,去第二层类容放到字典中去0
- NSDictionary*weatherInfo=[rootDicobjectForKey:@"weatherinfo"];
- //取值打印
- NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);
- NSURL*url=[NSURLURLWithString:@"http://m.weather.com.cn/data/101180701.html"];
- NSError*error=nil;
- NSString*jsonString=[NSStringstringWithContentsOfURL:urlencoding:NSUTF8StringEncodingerror:&error];
- SBJsonParser*parser=[[SBJsonParseralloc]init];
- NSDictionary*rootDic=[parserobjectWithString:jsonStringerror:&error];
- NSDictionary*weatherInfo=[rootDicobjectForKey:@"weatherinfo"];
- NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);
- NSError*error;
- //加载一个NSURL对象
- NSURLRequest*request=[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
- //将请求的url数据放到NSData对象中
- NSData*response=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil];
- //iOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
- NSDictionary*weatherDic=[NSJSONSerializationJSONObjectWithData:responseoptions:NSJSONReadingMutableLeaveserror:&error];
- //weatherDic字典中存放的数据也是字典型,从它里面通过键值取值
- NSDictionary*weatherInfo=[weatherDicobjectForKey:@"weatherinfo"];
- NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);
- //打印出weatherInfo字典所存储数据
- NSLog(@"weatherInfo字典里面的内容是--->%@",[weatherInfodescription]);
4.运行结果(如果想知道每次字符串和字典间取值情况,只需NSLog打印输出就行):
1、取值时发生应用程序崩溃,获取值不正确
有时我们从字典中获取了这样的数据,感觉比较郁闷,并未显示中文,这种情况是我们把数据放到字典中,编码方式是UTF8,取值打印出来的时候就成中文了
在解析出来数据后我想这样取值,
NSDictionary*weatherInfo = [rootDicobjectForKey:@"weatherinfo"];
NSArray*weatherArray = [rootDicobjectForKey:@"weatherinfo"];
for(NSDictionary*dicinweatherArray) {
NSLog(@"----->%@",dic);
}
打印出来的dic数据是这样的
NSLog(@"----->%@",[dicobjectForKey:@"city"]);来取出city的值,但是应用程序崩溃
xmlParser = [[NSXMLParser alloc] initWithData:weatherReponseData];
[xmlParsersetDelegate:self];
[xmlParsersetShouldProcessNamespaces:NO];
[xmlParsersetShouldReportNamespacePrefixes:NO];
[xmlParsersetShouldResolveExternalEntities:NO];
// 启动解析命令
- (void)startParse{
// 开始解析
[xmlParserparse];
}
// 设定委托方法
#pragma mark NSXMLParserDelegate
#pragma mark xml parser delegate
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSCharacterSet *whitespace = [NSCharacterSetwhitespaceCharacterSet];
string = [string stringByTrimmingCharactersInSet:whitespace];
if (![string isEqualToString:@"\n"]) {
[xmlWeatherStringArrayaddObject:string];
}
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSLog(@"%@", [parseError description]);
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
[selfoutputParseInfo];
//取出xml中数据后提取信息
[selfsplitXmlWeatherInfo];
}