用JSON和XML方法解析查询城市的天气情况

来源:互联网 发布:c语言数组转字符串 编辑:程序博客网 时间:2024/05/16 09:03

刚刚接触JSON解析和XML解析,挺兴奋的,就用JSON解析写了一个关于查询天气这样一个小功能,算是先练练手吧,不过程序中有点漏洞,如果大虾们能花点时间帮忙改正一下,那就真是感激不尽了,虽然不完美,但是对于初学者应该会有一点帮助,废话就不多说了,下面看看程序吧。

这个是头文件 

#import <Foundation/Foundation.h>@interface viewController : UIViewController@property(nonatomic,retain) NSString *cityname;@property(nonatomic,retain) NSString *cityid;@property(strong,nonatomic) NSMutableDictionary *mutArray;@property (nonatomic,retain) IBOutlet UITextView *txtView;//表示的是用来显示天气的信息@property (nonatomic,retain) IBOutlet UITextField *searchtext;//表示的是你想输入的城市名称,看一下他的类型就知道了@property (nonatomic,retain) IBOutlet UIButton *button;//这个是查询按钮   -(IBAction)search:(id)sender;  //实现查询功能的函数-(IBAction)backgroundTap:(id)sender;-(IBAction)textFieldDone:(id)sender;-(NSMutableArray *)XML; //解析XML数据的时候用@end

再来看看.m文件

这些是必不可少的内容 JSON解析用到的三个库有JSONKit ,SBJson ,TouchJson  XML解析用到的库有TBXML.h 

TBXML.m  NSDataAdditions.h   NSDataAdditions.m 这四个文件  我在头文件中都加载过了

#import "viewController.h"#import "TouchJson/JSON/CJSONDeserializer.h"#import "SBJson/SBJson.h"#import "JSONKit/JSONKit.h"#import "TBXML.h"@implementation viewController@synthesize cityname;@synthesize cityid;@synthesize txtView;@synthesize searchtext;@synthesize button;@synthesize mutArray;-(void)viewDidLoad{    [super viewDidLoad];    self.searchtext.placeholder=@"please input the city name : ";    self.searchtext.borderStyle = UITextBorderStyleRoundedRect;    //placeholder是给UITextField的输入框里添加灰色的提示语句的    //borderStyle是设置了输入框的形状的}

-(NSMutableArray *)XML{    NSMutableArray *array=[[NSMutableArray alloc]init];       /* NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"xml"];      NSData *data = [NSData dataWithContentsOfFile:path];      NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];      string = [string stringByReplacingOccurrencesOfString:@"encoding=\"gb2312\"" withString:@""];      NSData *newData = [string dataUsingEncoding:NSUTF8StringEncoding];      TBXML *tbXml = [TBXML tbxmlWithXMLData:newData];   */       /* TBXML *tbXml = [TBXML tbxmlWithXMLData:[NSData dataWithContentsOfFile:@"city.xml"]];*/       /* TBXML *tbXml = [[TBXML tbxmlWithXMLFile:@"city.xml"] retain]; //用这种方法时  必需用retain */        //上面的三种方法都是可以用的 都能得到 xml  三种方法最后都跟上TBXMLElement * root = tbXml.rootXMLElement;就行了 如下面的:    //用这种方法时  必需用retain 如果用上面的newData 则不必用retain    TBXML *tbXml = [[TBXML tbxmlWithXMLFile:@"city.xml"] retain];     TBXMLElement * root = tbXml.rootXMLElement;        if  (root)     {        //表示在根目录下找到@“city”这个健        TBXMLElement *info = [TBXML childElementNamed:@"city" parentElement:root];        while (info != nil)         {            NSMutableDictionary *dict = [NSMutableDictionary dictionary];            TBXMLElement *pName = [TBXML childElementNamed:@"cityname" parentElement:info];            TBXMLElement *pID = [TBXML childElementNamed:@"cityid" parentElement:info];                        //上面的这两行是访问@“city”下的所有内容                        self.cityname = [TBXML textForElement:pName];            self.cityid = [TBXML textForElement:pID];            [dict setObject:self.cityid forKey:@"id"];            [dict setObject:self.cityname forKey:@"name"];                       //上面的这两行把解析出来的数据存放到字典中                          [array addObject:dict];                        //上面的这行将字典存放到一个数组中 方便在下个函数中                        info = [TBXML nextSiblingNamed:@"city" searchFromElement:info];            //最后的这一句的作用是继续寻找下一个XML中键值为@"city"的内容                     }           }        return array;}

在把xml文件加载到工程中的时候 记得要把它加载到主目录下,就是存放AppDelegate.h那个文件的目录下 ,当时做这个程序的时候就在这个地方栽了大跟头,

xml文件明明加载到工程中了但就是找不到,后来我试着把xml文件加载到主目录下,结果成功了。不过你们做的时候,可以试一试,验证一次。

-(IBAction)search:(id)sender{    // NSURL *url=[NSURL URLWithString:@"http://api.liqwei.com/chinese/?language=gb|py&content=汉字.html"];       NSArray *array = [[NSArray alloc]initWithArray:[self XML]];  /* NSArray *keys=[array allKeys];   遍历字典中的value用key  这与下面的不一样 下面是从数组中遍历字典    for (NSString *key in keys)    {         NSString *result=[NSString stringWithFormat:@"key=%@,value=%@",key,[array objectForKey:key]];          NSLog(@"%@",result);    }  */   for(NSDictionary *dict in array)   {           if([searchtext.text isEqualToString:[dict objectForKey:@"name"]])      {          NSString *string = [NSString stringWithFormat:@"http://m.weather.com.cn/data/%@.html",[dict objectForKey:@"id"]];          NSURL *url = [NSURL URLWithString:string];   //得到官方提供的官方接口            NSError *error;          NSString *jsonString = [NSString stringWithContentsOfURL:url                                                           encoding:NSUTF8StringEncoding                                                              error:&error];         // NSLog(@"jsonString------>%@",jsonString);          //下面用JSON来解析网址中所提供的内容                   NSDictionary *rootDic = [[CJSONDeserializer deserializer]                                  deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding]                                   error:&error];         NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];                   // 这里想添加什么 就按照网址中所提供的内容 添加自己想要的  还有就是格式也可以自己改变                   txtView.text = [NSString stringWithFormat:@"日期: %@  %@ \n 城市:%@  \n天气状况:%@ \n 温度:%@  \n 建议:%@",                         [weatherInfo objectForKey:@"date_y"],                         [weatherInfo objectForKey:@"week"],                         [weatherInfo objectForKey:@"city"],                          [weatherInfo objectForKey:@"weather1"],                          [weatherInfo objectForKey:@"temp1"],                         [weatherInfo objectForKey:@"index_d"]];      }   }       [sender resignFirstResponder];  //输入完城市名之后点击enter健 键盘也会消失}

-(IBAction)backgroundTap:(id)sender     //点击屏幕时 键盘会下去{    [searchtext resignFirstResponder];}-(IBAction)textFieldDone:(id)sender  //点击键盘的return健会返回{    [sender resignFirstResponder];}

后面的这两个函数是让虚拟键盘划下去的意思,不过要注意,在xib文件中要把view的基类修改成UIControl,不再是UIView

而且textField不能直接连接到File's Owner上,因为模拟器默认的向touch Down touch up inside可能与自己想要的连接

事件不相符,所以要从touch Down touch up inside等这些事件中选择自己想要的,直接把他们与File's Owner相连接 第一个

要选择touch Down事件  第二个方法要选择Did End on Exit这个时间


原创粉丝点击