4_1網絡學習第一天后感--網絡數據下載
1、網絡數據下載包括同步下載和異步下載,一般是使用異步下載,異步下載可以利用NSURLConnection這個類。
2、有關數據格式,有JSON格式(多數)、xml格式。JSON格式如下:
{} 代表字典,[] 代表數組 ,“” 代表字符串 , 100 代表NSNumber
3、分析網絡接口
如:@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="
http:// (地址使用協議) iappfree.candou.com (主機地址) 8080 (主機端口)
free/applications/limited(網絡程序文件路徑) ?currency=rmb&page=1&category_id= (程序參數)
4、NSURLConnection的同步下載代碼:
-(void)testNSURLConnectionSyncDownloadData{ //限免頁面接口 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(@"下載失敗"); }}
5、NSURLConnection的異步下載代碼:
-(void)testNSURLConnectionAsyncDownloadData{ _data=[[NSMutableData alloc]init]; //限免頁面接口 NSString *urlString=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //發起一個異步URL請求 //異步:執行了方法之后,開始下載 _connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self startImmediately:YES]; }//下面是<NSURLConnectionDataDelegate>代理方法//接收到服務器響應執行-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"接收到服務器響應執行");}//接收到數據的時候執行//注意:當數據比較大,可能會多次執行-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//當數據下載完成了-(void)connectionDidFinishLoading:(NSURLConnection *)connection{// NSLog(@"str =%@",[[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding]); //解析JSON (把JSON轉化為NSArray或NSDictionary NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil]; NSArray *appList=dict[@"applications"]; for (NSDictionary *appDict in appList) { NSLog(@"name = %@",appDict[@"name"]); }}//下載失敗-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"error =%@",error);}
6、封裝NSURLConnection(重點)
先創建一個NSObject類,
#import <Foundation/Foundation.h>@interface ZJHttPRequset : NSObject//data用來保存下載的數據@property (nonatomic,copy) NSMutableData *data;//傳人一個網站,下載完成之后,執行target中action的方法-(void)requestWithUrl:(NSString *)url target:(id)target action:(SEL)action;@end
#import "ZJHttpRequset.h"#import "AppModel.h"//消除performSelector的警告#pragma clang diagnostic ignored "-Warc-performSelector-leaks"//類擴展,有些實例變量內部使用,不想放在頭文件,就可以放在類擴展里面。@interface ZJHttpRequset ()<NSURLConnectionDataDelegate>{ NSURLConnection *_connection; //用來保存存進來的url target action NSString *_url; id _target; SEL _action;}@end@implementation ZJHttpRequset-(void)requestWithUrl:(NSString *)url target:(id)target action:(SEL)action{ //保存存進來的變量 _url=url; _target=target; _action=action; //記住要初始化data!!! _data=[[NSMutableData alloc]init]; //發起異步URL請求 _connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self startImmediately:YES];}//NSURLConnection代理方法//接收數據-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//下載完成了,執行方法-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (_target&&[_target respondsToSelector:_action]) { [_target performSelector:_action withObject:self]; } //這里面的Object就是這個類本身,目的是把接收到的data傳遞}
再傳入網絡接口,利用這個封裝好的NSURLConnection類接收
@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; //數據接口 NSString *urlString=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //初始化數組(tabelView的數據總數組) _dataArray =[NSMutableArray array]; //初始化自封裝好的NSURLConnection類 _request=[[ZJHttpRequset alloc]init]; [_request requestWithUrl:urlString target:self action:@selector(dealDownloadFinish:)]; //創建表視圖 [self createTableView];}//接收完成之后會觸發的方法(在自封裝的URL類中 使用PerformSelector)-(void)dealDownloadFinish:(ZJHttpRequset *)request{ //JSON解析,(獲得的是數組還是字典,需要在JASON軟件中查看) NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil]; NSArray *appList=dict[@"applications"]; //利用數據模型保存網絡接口下的數據,然后把模型添加到tableView總數組 for (NSDictionary *appDict in appList) { AppModel *model=[[AppModel alloc]initWithDict:appDict]; [_dataArray addObject:model]; } //下載完數據,更新了總數組,一定要刷新tableview!!! [_tableView reloadData];}
7、作業
scrollView滑動
//第一步:初始化,從網絡接口下載數據-(void)createScrollView{ _allData1=[NSMutableArray array]; //陳奕迅網絡接口 NSString *urlString=@"http://mapi.damai.cn/hot201303/nindex.aspx?cityid=0&source=10099&version=30602"; _request1 =[[LCHttpRequest alloc]init]; [_request1 requestUrl:urlString withTarget:self andAction:@selector(scrollViewDownload:)]; }//第二步:下載完成后觸發的方法,把下載好的data 存入總數組-(void)scrollViewDownload:(LCHttpRequest *)request{ NSArray *arr=[NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil]; for (NSDictionary *dict in arr) { NSString *str=dict[@"Pic"]; [_allData1 addObject:str]; } [self loadImage];}//第三步:根據下載的總數組,改變ScrollView的contenSize 同時設置其imageView-(void)loadImage{ _scrollView.contentSize=CGSizeMake(320*_allData1.count, 0); for (int i=0; i<_allData1.count; i++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(320*i, 0, 320, 165)]; NSString *str= _allData1[i]; [imageView setImageWithURL:[NSURL URLWithString:str]]; [_scrollView addSubview:imageView]; } //設置pageControl _pageControl.numberOfPages=_allData1.count; _pageControl.enabled=NO; [self.view bringSubviewToFront:_pageControl]; _pageControl.pageIndicatorTintColor=[UIColor redColor]; //啟動定時器,讓scroView滑動 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scrollViewMove) userInfo:nil repeats:YES];}//定時器觸發的方法-(void)scrollViewMove{ CGPoint pp=_scrollView.contentOffset; if (pp.x==320*(_allData1.count-1)) { pp.x=0; _scrollView.contentOffset=pp; } else{ pp.x+=320; [UIView animateWithDuration:2.0 animations:^{ _scrollView.contentOffset=pp; }]; }}//<UIScrllViewDelegate> 代理方法讓pageControl跟著移動-(void)scrollViewDidScroll:(UIScrollView *)scrollView{ int page =scrollView.contentOffset.x/320; _pageControl.currentPage=page;}
新聞熱點
疑難解答