文章出處
文章列表
這一節講如何發起網絡請求。
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://blog.csdn.net/enuola/article/details/7904090
先給出一個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]; }
文章列表
全站熱搜