標籤:
IOS之網路資料下載和JSON解析
簡介
在IOS中的開發中,應用類型大體可分為兩類,一是本地應用,一般利用本機資料載入內容,二是網路應用,利用服務端的傳送來的資料經過解析後載入內容,下文將介紹網路應用開發的基礎知識。將涉及下面幾點知識:
1.利用NSURL等類進行資料下載;
2.JSON的資料格式和JSON解析;
3.利用第三方庫SDWebImage顯示圖片。
一、NSURL類 1、NSURL相關類介紹
(1)NSURL:請求地址
(2)NSURLRequest:封裝一個請求地址,儲存發給伺服器的全部資料
(3)NSMutableURLRequest:NSURLRequest的子類
(4)NSURLConnection:負責發送請求,建立用戶端和伺服器的串連。發送NSURLRequest的資料給伺服器,並收集來自伺服器的響應資料
2、NSURL相關類使用
(1)建立一個NSURL對象,佈建要求路徑(佈建要求路徑)
(2)傳入NSURL建立一個NSURLRequest對象,佈建要求頭和請求體(建立請求對象)
(3)使用NSURLConnection發送NSURLRequest(發送請求)
3、使用相關
利用NSURL可以建立同步請求或者非同步請求,同步請求會使應用一直處於等待伺服器返回資料狀態,如果伺服器,沒有返回資料,那麼在主線程UI會卡住不能繼續執行操作,進入所謂的假死,非同步請求則可以避免這種情況;
(1)同步請求
重申一下發送請求的步驟
1.佈建要求路徑
2.建立請求對象
3.發送請求 下面是範例程式碼
NSString *urlString = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //發送同步URL請求 //NSURLRequest URL請求對象 NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; if(error == nil) { NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"str = %@",str); } else { NSLog(@"下載失敗"); }
此處 http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id= 為網路介面,通過該網路介面產生請求和建立串連
(2)非同步請求
非同步請求的實現方法有兩種,一是利用代碼塊Block的回調,二是利用代理協議,此處只簡單介紹代碼塊的回調使用
代碼塊Block的非同步請求:
範例程式碼
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="]]; NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];//擷取主線程 [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { }];
利用 sendAsynchronousRequest: queue: completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {} 方法發送非同步請求,代碼塊的內容一般是解析下載的資料然後重新整理UI介面,因為UI介面的重新整理一定要在主線程中完成,所以建立了主操作隊列進行重新整理;
代理協議非同步請求:
範例程式碼
-(void)testNSURLConnectionAsyncDownloadData{ NSString *urlString = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //初始化 _data = [[NSMutableData alloc] init]; //發起了一個非同步URL串連請求 //非同步: 執行了方法之後開始下載,立即返回 // 下載過程在後台(多線程)執行 _connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self startImmediately:YES]; NSLog(@"initWithRequest 執行完成"); }//代理方法: 接收到伺服器響應執行-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"接收到伺服器響應執行");}//代理方法: 接收到資料的時候執行//注意: 當資料比較大, 可能多次執行-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//代理方法: 資料下載完成了-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSString *str = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding]; NSLog(@"str = %@",str); }-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"error = %@",error);}
建立串連前需要遵守NSURLConnectionDataDelegate協議,NSURL相關類的使用簡單,按照指定步驟進行即可。
二、JSON相關1、JSON基本知識
伺服器返回給應用的資料一般有兩種格式,一是JSON格式,二是XML格式,此處將介紹JSON格式。
JSON的資料格式相當簡潔輕量,因而易於解析,下面是一段JSON的範例程式碼
{ "applications": [ { "applicationId": "455680974", "slug": "rhythm-repeat", "name": "\u8282\u594f\u91cd\u590d", "releaseDate": "2014-07-01", "version": "2.3", "description": "\u754c\u9762\u6e05\u65b0\u7b80\u5355\u7684\u97f3\u4e50\u8282\u594f\u6e38\u620f\u3002\u6e38\u620f\u7684\u64cd\u4f5c\u975e\u5e38\u7b80\u5355\uff0c\u53ea\u9700\u6839\u636e\u63d0\u793a\u4f9d\u6b21\u70b9\u51fb\u76f8\u5e94\u7684\u56fe\u6807\u5373\u53ef\uff0c\u5171\u6709\u4e09\u79cd\u4e50\u66f2\u9009\u62e9\u3002", "categoryId": 6014, "categoryName": "Game", "iconUrl": "http:\/\/photo.candou.com\/i\/114\/55b07f3725eae8b3cafc9bce10d16e46", "itunesUrl": "http:\/\/itunes.apple.com\/cn\/app\/rhythm-repeat\/id455680974?mt=8", "starCurrent": "4.0", "starOverall": "4.0", "ratingOverall": "0", "downloads": "3217", "currentPrice": "0", "lastPrice": "12", "priceTrend": "limited", "expireDatetime": "2015-04-06 01:50:41.0", "releaseNotes": "Multi-Touch bug fixed", "updateDate": "2014-10-17 15:45:27", "fileSize": "16.69", "ipa": "1", "shares": "390", "favorites": "273" },
解析JSON就要把JSON 轉換為 OC資料類型
大括弧{}對應OC中的NSDictionary,中括弧[]對應OC中的NSArray,“”雙引號對應OC中的NSString,6014對應OC中的NSNumber
2、JSON解析
在iOS中,JSON的常見解析方案有多種:
(1)第三方架構:JSONKit、SBJson、TouchJSON
(2)蘋果原生(內建):NSJSONSerialization
下面介紹NSJSONSerialization的使用
NSJSONSerialization的常見方法
(1)JSON資料 ——》 OC對象
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
JSON資料的外部為{}時,傳回型別設定為NSDictionary,為[]時,傳回型別為NSArray;
其中data為從伺服器接受的資料;
(2)OC對象 ——》 JSON資料
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
範例程式碼
- (void)dealDownLoad:(MyHttpRequest *)request{ NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil]; NSArray *arrTemp = dict[@"applications"]; [_dataArray removeAllObjects]; for (NSDictionary *dicTemp in arrTemp) { AppDataModel *modal = [[AppDataModel alloc] init]; modal.applicationID = dicTemp[@"applicationId"]; modal.iconUrl = dicTemp[@"iconUrl"]; modal.name = dicTemp[@"name"]; [_dataArray addObject:modal]; } [_tableView reloadData];}
JSON的解析簡單,此處不多贅述了
三、SDWebImage使用
第三庫SDWebImage不支援ARC,所以使用前需要進行配置,給庫內的所有檔案設定-fno-objc-arc,
利用庫內的方法setImageWithURL,傳入一個圖片URl即可以在需要顯示圖片時進行載入
四、總結
本文涉及的知識不算難懂,多練習就好了,另外本人目前水平有限,如有錯誤之處,還請各位在下面評論指出,謝謝!
IOS之網路資料下載和JSON解析