这一节讲如何发起网络请求。
iOS用于调用MobileAPI的第三方组件很多,我们这里采用的是以下组件:
1)ASIHTTPRequest,用于请求MobileAPI:http://allseeing-i.com/ASIHTTPRequest/
2)SBJson,2.3版本,用于解析JSON:http://stig.github.com/json-framework/
由于我们在MyLib中引用了SBJson,它里面有一个Category名为NSString+SBJSON,为了能使用它,请在
MyLib和MyApp项目中的Other Linker Falgs设为-all_load。
这一节内容非常芜杂,我将其分为以下几个部分:
1)将返回JSON格式的数据转换实体类
2)网络请求的封装——汇总API的配置文件
3)网络请求的封装——RemotingService横空出世
4)网络请求的封装——一些善后工作
5)数据缓存
6)自动重试
7)自动化实体生成器
此外,我们会在后续的章节,介绍Cookie的处理和时间校准机制,它们都和调用MobileAPI息息相关。
本文采取的例子是开源免费天气预报接口API以及全国所有地区代码!!(国家气象局提供):http://mobile.51cto.com/hot-409995.htm
先给出一个ASIHTTPRequest+SBJson的例子:YoungHeart-Chapter-05.zip
关键代码如下所示:
- - (void)loadData {
- NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/sk/101010100.html"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDelegate:self];
- [request startAsynchronous];
- }
- - (void)requestFinished:(ASIHTTPRequest *)request {
- NSString *jsonStr =[request responseString];
- SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
- NSMutableDictionary *dict = [jsonParser objectWithString:jsonStr];
- NSLog(@"%@",dict);
- [jsonParser release];
- id jsonValue = [jsonStr JSONValue];
- }
- - (void)requestFailed:(ASIHTTPRequest *)request {
- UIAlertView* alertView = [[UIAlertView alloc]initWithTitle: @"粗锉啦" message: @"Network Error" delegate: self cancelButtonTitle: @"OK" otherButtonTitles: nil];
- [alertView show];
- [alertView release];
- }