RootViewController .h
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController {
NSMutableData *responseData;
/* 用来存放从服务器传过来的一切数据 */
NSURLConnection *myConnection;
/* 存放和服务器连接的对象 */
}
@end
RootViewController.m
#import "RootViewController.h"
#import "JSON.h"
@interface NSString (Chinese)
- (NSString *) urlEncoding;
@end
@implementation NSString (Chinese)
- (NSString *) urlEncoding
{
NSString *retStr;
retStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)self,
NULL,
(CFStringRef)@";/?:@&=$+{}<>,",
kCFStringEncodingUTF8);
return [retStr autorelease];
}
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/* 把一个字符串转化成在网络上传输的标准字符串 */
- (NSString *) urlEncoding:(NSString *)str
{
NSString *retStr;
retStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)str,
NULL,
(CFStringRef)@";/?:@&=$+{}<>,",
kCFStringEncodingUTF8);
return [retStr autorelease];
}
/* 1. 同步网络下载 */
- (void) downloadSync
{
NSString *str = @"http://api.douban.com/book/subjects?q=maozedong&start-index=1&max-results=10&apikey=04f1ae6738f2fc450ed50b35aad8f4cf&alt=json";
NSURL *url = [NSURL URLWithString:str];
/* 1. 把字符串转化为NSURL对象 */
NSError *error = nil;
NSString *jsonStr =
[NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
/* 2. 同步下载url里面的内容存放在jsonStr中 */
NSLog(@"json:%@", jsonStr);
}
- (void) downloadAsync
{
NSString *keyWord = @"毛泽东";
NSString *newKeyWord = [keyWord urlEncoding];
NSString *newKeyWord2 = [self urlEncoding:keyWord];
NSString *str = @"http://api.douban.com/book/subjects?q=maozedong&start-index=1&max-results=10&apikey=04f1ae6738f2fc450ed50b35aad8f4cf&alt=json";
NSURL *url = [NSURL URLWithString:str];
/* 0. 创建responseData数据区 */
responseData = [[NSMutableData alloc] initWithLength:0];
/* 1. 构造网络请求 30s超时时间 */
NSURLRequest *myRequest =
[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
/* 2. 建立网络连接 */
myConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
/* 以请求myRequest来建立一个网络连接,并且使用代理self来
接收该连接传过来的数据 */
/* 3. 让网络指示器显示进度条 */
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//[self downloadSync];
[self downloadAsync];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Network connection
/* 1. 网络开始接收数据 */
/* 网络响应头接收完成,真正数据开始马上要来到了 */
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"finish receive response");
NSLog(@"response is %@", response);
NSLog(@"begin to receive real data");
[responseData setLength:0];
}
/* 2. 网络正在接收数据 */
/* data参数就是系统每次接收一大段数据就会调用该方法 */
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
static int index;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
/* 把data转化成字符串 */
NSLog(@"receive index %d datastring is %@",
index++, str);
[str release];
[responseData appendData:data];
/* 把网络传给我们的数据data附加到responseData之后即可 */
}
/* 2. 网络数据接收完成 */
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"receive finish");
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"str is %@", str);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[myConnection release];
/* 使用json解析 */
NSDictionary *jsonParser = [str JSONValue];
/* 通过str JSONValue就转化成 json的格式 */
/*
"opensearch:totalResults": {
"$t": "3"
},
"opensearch:startIndex": {
"$t": "1"
},
"opensearch:itemsPerPage": {
"$t": "10"
},
*/
NSDictionary *t1 = [jsonParser objectForKey:@"opensearch:totalResults"];
NSString *t2 = [t1 objectForKey:@"$t"];
NSLog(@"$t is %@", t2);
int startIndex = [[[jsonParser objectForKey:@"opensearch:startIndex"] objectForKey:@"$t"] intValue];
int itemsPerPage = [[[jsonParser objectForKey:@"opensearch:itemsPerPage"] objectForKey:@"$t"] intValue];
NSLog(@"startIndex %d itemsPerPage %d",
startIndex, itemsPerPage);
NSArray *books = [jsonParser objectForKey:@"entry"];
for (NSDictionary *perBook in books) {
NSString *name = [[perBook objectForKey:@"title"] objectForKey:@"$t"];
NSString *author = [[[[perBook objectForKey:@"author"] objectAtIndex:0] objectForKey:@"name"] objectForKey:@"$t"];
NSLog(@"book name %@ author %@", name, author);
}
[str release];
}
@end