無(wú)線客戶端框架設(shè)計(jì)(5):調(diào)用MobileAPI的設(shè)計(jì)(iOS篇)
這一節(jié)講如何發(fā)起網(wǎng)絡(luò)請(qǐng)求。
iOS用于調(diào)用MobileAPI的第三方組件很多,我們這里采用的是以下組件:
1)ASIHTTPRequest,用于請(qǐng)求MobileAPI:http://allseeing-i.com/ASIHTTPRequest/
2)SBJson,2.3版本,用于解析JSON:http://stig.github.com/json-framework/
由于我們?cè)贛yLib中引用了SBJson,它里面有一個(gè)Category名為NSString+SBJSON,為了能使用它,請(qǐng)?jiān)?/p>
MyLib和MyApp項(xiàng)目中的Other Linker Falgs設(shè)為-all_load。
這一節(jié)內(nèi)容非常蕪雜,我將其分為以下幾個(gè)部分:
1)將返回JSON格式的數(shù)據(jù)轉(zhuǎn)換實(shí)體類
2)網(wǎng)絡(luò)請(qǐng)求的封裝——匯總API的配置文件
3)網(wǎng)絡(luò)請(qǐng)求的封裝——RemotingService橫空出世
4)網(wǎng)絡(luò)請(qǐng)求的封裝——一些善后工作
5)數(shù)據(jù)緩存
6)自動(dòng)重試
7)自動(dòng)化實(shí)體生成器
此外,我們會(huì)在后續(xù)的章節(jié),介紹Cookie的處理和時(shí)間校準(zhǔn)機(jī)制,它們都和調(diào)用MobileAPI息息相關(guān)。
本文采取的例子是開源免費(fèi)天氣預(yù)報(bào)接口API以及全國(guó)所有地區(qū)代碼!?。▏?guó)家氣象局提供):http://mobile.51cto.com/hot-409995.htm
先給出一個(gè)ASIHTTPRequest+SBJson的例子:YoungHeart-Chapter-05.zip
關(guān)鍵代碼如下所示:
- - (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];
- }