主要是显示地理位置和天气以及温度。对网络请求下来的json数据进行解析。
#import "ViewController.h"
#define kWeatherUrl @"http://www.weather.com.cn/data/cityinfo/101010100.html"
@interface ViewController ()<NSURLConnectionDataDelegate>{
NSMutableData *_downLoadData; //存储接受的数据
}
@property (weak, nonatomic) IBOutlet UILabel *cityLabel; //城市
@property (weak, nonatomic) IBOutlet UILabel *weatherLabel; //天气
@property (weak, nonatomic) IBOutlet UILabel *tempLabel; //温度,显示格式为-2℃~6℃
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_downLoadData = [[NSMutableData alloc] init];
//No.1
//开始写代码,网络请求,请求 kWeatherUrl 的数据
NSURL *url=[NSURL URLWithString:kWeatherUrl];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
//end_code
}
//No.2
//开始写代码,补全下列NSURLConnectionDataDelegate的代理函数
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// _downLoadData = nil;
NSHTTPURLResponse * resp = (NSHTTPURLResponse *)response;
NSLog(@"%ld", (long)resp.statusCode);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_downLoadData appendData:data];
// NSLog(@"%@", data);
}
//end_code
//No.3
//开始写代码,json解析,json形式如下:{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"-2℃","temp2":"6℃","weather":"晴","img1":"n0.gif","img2":"d0.gif","ptime":"18:00"}}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (_downLoadData) {
NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:_downLoadData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary *dict = rootDict[@"weatherinfo"];
_cityLabel.text = dict[@"city"];
_weatherLabel.text = dict[@"weather"];
_tempLabel.text = [NSString stringWithFormat:@"%@~%@", dict[@"temp1"], dict[@"temp2"]];
}
}
//end_code
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"下载失败:%@",error.userInfo);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
利用XML解析类库GData,通过XPath方式,处理XML格式数据。
#import "ViewController.h"
#import "GDataXMLNode.h"
#import "BookModel.h"
#import "BookTableViewCell.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@end
@implementation ViewController{
NSMutableArray * _dataSource;
UITableView * _tableView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self parsingXmlForXPath];
[self prepareTableView];
}
-(void)parsingXmlForXPath
{
_dataSource = [[NSMutableArray alloc]init];
//No.1
//开始写代码,读取xml.txt文件,实现XML的解析(使用XPath方式分会多哦),结果存入名为booksArray的数组。xml.txt内容如下:
/*
<?xml version="1.0" encoding="utf-8" ?>
<root>
<books>
<book id="1" language="ch">
<name>乔布斯传</name>
<auther>
<name>沃尔特·艾萨克森</name>
</auther>
<price>80.00</price>
<summary>介绍乔布斯传奇的一生</summary>
</book>
<book id="2" language="ch">
<name>呐喊</name>
<auther>
<name>鲁迅</name>
</auther>
<price>12.00</price>
<summary>揭示了中国的社会面貌,控诉了封建制度的罪恶,喊出了“五四”时期革命者的心声。它反映了“五四”彻底不妥协地反封建主义的革命精神,适应了中国革命从旧民主主义向新民主主义转变的需要,在中国现代文化史和文学史上占有重要地位!</summary>
</book>
<book id="3" language="en">
<name>哈利波特</name>
<auther>
<name>JK罗琳</name>
</auther>
<price>365.00</price>
<summary>主人公哈利·波特在霍格沃茨魔法学校六年的学习生活和冒险故事。</summary>
</book>
</books>
</root>
*/
NSString *path = [[NSBundle mainBundle] pathForResource:@"xml.txt" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:path];
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
NSString *xPath = @"/root/books/book";
NSArray *booksArray = [document nodesForXPath:xPath error:nil];
//end_code
for (GDataXMLElement * book in booksArray) {
BookModel * bookModel = [[BookModel alloc]init];
NSArray * bookNames = [book elementsForName:@"name"];
GDataXMLElement * bookName = [bookNames lastObject];
bookModel.bookName = bookName.stringValue;
NSArray * authers = [book elementsForName:@"auther"];
GDataXMLElement * auther = [authers lastObject];
NSArray * autherNames = [auther elementsForName:@"name"];
GDataXMLElement * autherName = [autherNames lastObject];
bookModel.bookAutherName = autherName.stringValue;
NSArray * prices = [book elementsForName:@"price"];
GDataXMLElement * price = [prices lastObject];
bookModel.bookPrice = price.stringValue;
NSArray * summarys = [book elementsForName:@"summary"];
GDataXMLElement * summary = [summarys lastObject];
bookModel.bookSummary = summary.stringValue;
[_dataSource addObject:bookModel];
}
}
-(void)prepareTableView{
self.automaticallyAdjustsScrollViewInsets = NO;
_tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
BookTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"book"];
if (!cell) {
cell = [[[NSBundle mainBundle]loadNibNamed:@"BookTableViewCell" owner:self options:nil]lastObject];
}
BookModel * bookModel = [_dataSource objectAtIndex:indexPath.row];
cell.bookNameLabel.text = bookModel.bookName;
cell.bookAutherNameLabel.text = bookModel.bookAutherName;
cell.bookPriceLabel.text = bookModel.bookPrice;
cell.bookSummaryLabel.text = bookModel.bookSummary;
NSString * string = ((BookModel *)[_dataSource objectAtIndex:indexPath.row]).bookSummary;
CGRect rect = [string boundingRectWithSize:CGSizeMake(190, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:17]} context:nil] ;
cell.bookSummaryLabel.frame = CGRectMake(CGRectGetMinX(cell.bookSummaryLabel.frame), CGRectGetMinY(cell.bookSummaryLabel.frame), 190, rect.size.height);
cell.bookSummaryLabel.backgroundColor = [UIColor cyanColor];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString * string = ((BookModel *)[_dataSource objectAtIndex:indexPath.row]).bookSummary;
CGRect rect = [string boundingRectWithSize:CGSizeMake(190, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:17]} context:nil];
return 128 + rect.size.height;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end