#define DOUBANURL @"http://api.douban.com/book/subjects?q=mao&start-index=1&max-%20results=10&apikey=0f56d0e8157561512e0472b8406023f3&alt=json"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *path = DOUBANURL;
NSURL *pathURL = [NSURL URLWithString:path];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:pathURL];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[request release];
_myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
_myTableView.delegate = self;
_myTableView.dataSource = self;
[self.view addSubview:_myTableView];
}
在上面方法中,初始化url地址
NSURL *pathURL = [NSURL URLWithString:path];
创建客户端请求头
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:pathURL];
根据请求头创建网络连接
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
创建一个tableview来显示从网络上获取的数据,并设置自身为其数据源和委托
_myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
_myTableView.delegate = self;
_myTableView.dataSource = self;
[self.view addSubview:_myTableView];
在控制器头文件中遵守协议
NSURLConnectionDataDelegate,UITableViewDataSource,UITableViewDelegate
#pragma mark -
#pragma mark NSURLConnection Delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_data = [[NSMutableData alloc]initWithCapacity:0];
_dataArray = [[NSMutableArray alloc]initWithCapacity:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *dataStr = [[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
NSDictionary *dic = [dataStr JSONValue];
NSArray *array = [dic objectForKey:@"entry"];
//[[[[[jsonStr objectForKey:@"entry"]objectAtIndex:8] objectForKey:@"link"] objectAtIndex:2] objectForKey:@"@href"]
for (int i = 0; i < [array count]; i++) {
NSString *imgURL = [[[[array objectAtIndex:i] objectForKey:@"link"] objectAtIndex:2] objectForKey:@"@href"];
NSString *bookAuthod = [[[[[array objectAtIndex:i] objectForKey:@"author"] objectAtIndex:0] objectForKey:@"name"]objectForKey:@"$t"];
NSString *bookTitle = [[[array objectAtIndex:i] objectForKey:@"title"] objectForKey:@"$t"];
BookModel *model = [[BookModel alloc]init];
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
UIImage *img = [UIImage imageWithData:imgData];
model.image = img;
model.bookAuthod = bookAuthod;
model.bookName = bookTitle;
[_dataArray addObject:model];
[model release];
}
[_myTableView reloadData];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
这个委托方法在服务端响应头发回给客户端后调用
在该方法中初始化数据缓冲区
_data = [[NSMutableData alloc]initWithCapacity:0];
_dataArray = [[NSMutableArray alloc]initWithCapacity:0];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
这个委托方法是接收数据时会被调用
在该方法中将获取的网络数据放入数据缓冲区
[_data appendData:data];
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
这个委托方法在完成数据接收后被调用
在该方法中对数据缓冲区中的数据进行处理
NSDictionary *dic = [dataStr JSONValue];
这里使用了SBJSON这个第三库的方法
通过解析这里获得的json数据
将其存入模型类BookModel,在将这些对象存入数据源_dataArray
for (int i = 0; i < [array count]; i++) {
NSString *imgURL = [[[[array objectAtIndex:i] objectForKey:@"link"] objectAtIndex:2] objectForKey:@"@href"];
NSString *bookAuthod = [[[[[array objectAtIndex:i] objectForKey:@"author"] objectAtIndex:0] objectForKey:@"name"]objectForKey:@"$t"];
NSString *bookTitle = [[[array objectAtIndex:i] objectForKey:@"title"] objectForKey:@"$t"];
BookModel *model = [[BookModel alloc]init];
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
UIImage *img = [UIImage imageWithData:imgData];
model.image = img;
model.bookAuthod = bookAuthod;
model.bookName = bookTitle;
[_dataArray addObject:model];
[model release];
}
最后让表格视图reload一下
[_myTableView reloadData];
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
这个委托方法在获取数据发生错误时被调用
在这里不做介绍,目前已经获取数据源的数据了,接下来需要对表格视图进行配置
#pragma mark -
#pragma mark TableView DataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_dataArray count];
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 110;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifies = @"CellIdentifies";
BookCell *oneCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifies];
if (!oneCell) {
oneCell = [[[BookCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifies]autorelease];
}
BookModel *model = [_dataArray objectAtIndex:indexPath.row];
oneCell.bookImage.image = model.image;
oneCell.bookAuthod.text = model.bookAuthod;
oneCell.bookName.text = model.bookName;
return oneCell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
这里返回tableView显示的行数
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
这里返回tableView每行的高度
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
这里对每个单元格进行绘制
在这里我们使用了自定义的表格单元BookCell
static NSString *CellIdentifies = @"CellIdentifies";
BookCell *oneCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifies];
if (!oneCell) {
oneCell = [[[BookCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifies]autorelease];
}
BookModel *model = [_dataArray objectAtIndex:indexPath.row];
oneCell.bookImage.image = model.image;
oneCell.bookAuthod.text = model.bookAuthod;
oneCell.bookName.text = model.bookName;
return oneCell;
#import <Foundation/Foundation.h>
@interface BookModel : NSObject
{
UIImage *_image;
NSString *_bookName;
NSString *_bookAuthod;
}
@property (nonatomic,retain) UIImage *image;
@property (nonatomic,retain) NSString *bookName;
@property (nonatomic,retain) NSString *bookAuthod;
@end
#import "BookModel.h"
@implementation BookModel
@synthesize image = _image,bookName = _bookName,bookAuthod = _bookAuthod;
-(void)dealloc
{
[_image release];
[_bookName release];
[_bookAuthod release];
[super dealloc];
}
@end
以下是BookCell类的源码
#import <UIKit/UIKit.h>
@class BookModel;
@interface BookCell : UITableViewCell
{
UIImageView *_bookImage;
UILabel *_bookName;
UILabel *_bookAuthod;
}
@property (nonatomic,retain) UIImageView *bookImage;
@property (nonatomic,retain) UILabel *bookName;
@property (nonatomic,retain) UILabel *bookAuthod;
@end
#import "BookCell.h"
@implementation BookCell
@synthesize bookImage = _bookImage,bookName = _bookName,bookAuthod = _bookAuthod;
-(void)dealloc
{
[_bookName release];
[_bookImage release];
[_bookAuthod release];
[super dealloc];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
_bookImage = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 100, 100)];
_bookImage.contentMode = UIViewContentModeScaleAspectFit;
_bookImage.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:_bookImage];
_bookName = [[UILabel alloc]initWithFrame:CGRectMake(110, 30, 100, 60)];
_bookName.numberOfLines = 0;
_bookName.textAlignment = UITextAlignmentLeft;
_bookName.font = [UIFont boldSystemFontOfSize:17];
_bookName.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:_bookName];
_bookAuthod = [[UILabel alloc]initWithFrame:CGRectMake(200, 30, 100, 60)];
_bookAuthod.numberOfLines = 0;
_bookAuthod.font = [UIFont systemFontOfSize:14];
_bookAuthod.textAlignment = UITextAlignmentRight;
_bookAuthod.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:_bookAuthod];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
控制器头文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<NSURLConnectionDataDelegate,UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *_dataArray;
NSURLConnection *_connection;
NSMutableData *_data;
UITableView *_myTableView;
}
@end