在本文中筆者將要給你們介紹IOS中如何利用NSURLConnection從網絡上下載數據,如何解析從網絡下載下來的JSON數據格式,以及如何顯示實踐和圖片的異步下載顯示json
涉及到的知識點:數組
1.NSURLConnection異步下載和封裝;網絡
2.JSON格式和JSON格式解析;app
3.數據顯示和使用SDWebImage異步顯示圖片;異步
須要從網絡上獲取數據的應用工具
C/S結構ui
Client客戶端: 展現數據, 與用戶進行交互atom
Server服務端: 爲客戶端提供數據, 提供服務url
地址使用協議+主機地址+主機端口+網頁程序文件+程序參數spa
下載數據,解析數據,創建數據模型,使用視圖顯示,tabelView+自制Cell;圖片的異步下載SDWebImage;
NSString 的同步下載
NSError *error = nil; NSURL *url = [NSURL URLWithString:urlString]; NSString *content = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; if (error==nil) { NSLog(@"content = %@",content); } else { NSLog(@"下載失敗"); }
NSURLConnection 同步下載
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(@"下載失敗"); }
NSURLConection異步下載
@property (copy,nonatomic) NSMutableData *data; //做用: // 傳入網址, 下載完成執行後執行target對象中action方法 -(void)requestWithUrl:(NSString *)url target:(id)target action:(SEL)action; @interface ZJHttpRequest ()<NSURLConnectionDataDelegate> { NSURLConnection *_connection; NSString *_url; id _target; SEL _action; } @end @implementation ZJHttpRequest //做用: // 傳入網址, 下載完成執行後執行target對象中action方法 -(void)requestWithUrl:(NSString *)url target:(id)target action:(SEL)action { _url = url; _target = target; _action = action; //發起URL請求 _data = [[NSMutableData alloc] init]; _connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self startImmediately:YES]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [_data appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { //下載完成了, 執行保存的方法 if(_target && [_target respondsToSelector:_action]) { [_target performSelector:_action withObject:self]; } }
//JSON
//JavaScript Object Notation
/*
{
"count":20,
"data":[
"zhangsan",
"lisi",
"wangwu"
]
}
*/
//[] 表示數組,對應NSArray
//, 表示並列的數據
//{} 表示字典,對應NSDictionary
//: 表示鍵值對
//"ta" 表示字符串,對應NSString
//20 對應NSNumber
//JSON格式格式化工具
// Jason
// Json Editor
// 在線: http://www.kjson.com/
建立Model
解析JSON的數據
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil]; //NSLog(@"dict = %@",dict); NSArray *appList = dict[@"applications"]; for (NSDictionary *appDict in appList) { AppModel *model = [[AppModel alloc] init]; model.applicationId = appDict[@"applicationId"]; model.name = appDict[@"name"]; model.iconUrl = appDict[@"iconUrl"]; [_dataArray addObject:model]; } //下載數據刷新顯示 [_tableView reloadData];
建立UITabelView 跟自制Cell
-(void)createTableView { _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; _tableView.dataSource = self; _tableView.delegate = self; [self.view addSubview:_tableView]; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _dataArray.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellID = @"cell"; AppCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; if(cell == nil) { cell = [[AppCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID]; } //config cell AppModel *model = _dataArray[indexPath.row]; //cell.textLabel.text = model.name; cell.nameLabel.text = model.name; [cell.iconImageView setImageWithURL:[NSURL URLWithString:model.iconUrl]]; return cell; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 80; }
<1> 導入庫的文件
<2> 如何在ARC工程中使用非ARC的代碼???
解決: 在SDWebImage源碼文件中禁止ARC功能
工程配置-->Targets-->Build Phases--> Compile Source
搜索文件SD,Cache, 獲得的文件添加標誌 -fno-objc-arc
包含: #import "UIImageView+WebCache.h"