4_1網(wǎng)絡(luò)學(xué)習(xí)第一天后感--網(wǎng)絡(luò)數(shù)據(jù)下載
1、網(wǎng)絡(luò)數(shù)據(jù)下載包括同步下載和異步下載,一般是使用異步下載,異步下載可以利用NSURLConnection這個(gè)類。
2、有關(guān)數(shù)據(jù)格式,有JSON格式(多數(shù))、xml格式。JSON格式如下:
{} 代表字典,[] 代表數(shù)組 ,“” 代表字符串 , 100 代表NSNumber
3、分析網(wǎng)絡(luò)接口
如:@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="
http:// (地址使用協(xié)議) iappfree.candou.com (主機(jī)地址) 8080 (主機(jī)端口)
free/applications/limited(網(wǎng)絡(luò)程序文件路徑) ?currency=rmb&page=1&category_id= (程序參數(shù))
4、NSURLConnection的同步下載代碼:
-(void)testNSURLConnectionSyncDownloadData{ //限免頁面接口 NSString *urlString=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //發(fā)送同步URL請(qǐng)求 //NSURLRequest URL請(qǐng)求對(duì)象 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="; //發(fā)起一個(gè)異步URL請(qǐng)求 //異步:執(zhí)行了方法之后,開始下載 _connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self startImmediately:YES]; }//下面是<NSURLConnectionDataDelegate>代理方法//接收到服務(wù)器響應(yīng)執(zhí)行-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"接收到服務(wù)器響應(yīng)執(zhí)行");}//接收到數(shù)據(jù)的時(shí)候執(zhí)行//注意:當(dāng)數(shù)據(jù)比較大,可能會(huì)多次執(zhí)行-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//當(dāng)數(shù)據(jù)下載完成了-(void)connectionDidFinishLoading:(NSURLConnection *)connection{// NSLog(@"str =%@",[[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding]); //解析JSON (把JSON轉(zhuǎn)化為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(重點(diǎn))
先創(chuàng)建一個(gè)NSObject類,
#import <Foundation/Foundation.h>@interface ZJHttPRequset : NSObject//data用來保存下載的數(shù)據(jù)@property (nonatomic,copy) NSMutableData *data;//傳人一個(gè)網(wǎng)站,下載完成之后,執(zhí)行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"//類擴(kuò)展,有些實(shí)例變量?jī)?nèi)部使用,不想放在頭文件,就可以放在類擴(kuò)展里面。@interface ZJHttpRequset ()<NSURLConnectionDataDelegate>{ NSURLConnection *_connection; //用來保存存進(jìn)來的url target action NSString *_url; id _target; SEL _action;}@end@implementation ZJHttpRequset-(void)requestWithUrl:(NSString *)url target:(id)target action:(SEL)action{ //保存存進(jìn)來的變量 _url=url; _target=target; _action=action; //記住要初始化data!!! _data=[[NSMutableData alloc]init]; //發(fā)起異步URL請(qǐng)求 _connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self startImmediately:YES];}//NSURLConnection代理方法//接收數(shù)據(jù)-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//下載完成了,執(zhí)行方法-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (_target&&[_target respondsToSelector:_action]) { [_target performSelector:_action withObject:self]; } //這里面的Object就是這個(gè)類本身,目的是把接收到的data傳遞}
再傳入網(wǎng)絡(luò)接口,利用這個(gè)封裝好的NSURLConnection類接收
@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; //數(shù)據(jù)接口 NSString *urlString=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //初始化數(shù)組(tabelView的數(shù)據(jù)總數(shù)組) _dataArray =[NSMutableArray array]; //初始化自封裝好的NSURLConnection類 _request=[[ZJHttpRequset alloc]init]; [_request requestWithUrl:urlString target:self action:@selector(dealDownloadFinish:)]; //創(chuàng)建表視圖 [self createTableView];}//接收完成之后會(huì)觸發(fā)的方法(在自封裝的URL類中 使用PerformSelector)-(void)dealDownloadFinish:(ZJHttpRequset *)request{ //JSON解析,(獲得的是數(shù)組還是字典,需要在JASON軟件中查看) NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil]; NSArray *appList=dict[@"applications"]; //利用數(shù)據(jù)模型保存網(wǎng)絡(luò)接口下的數(shù)據(jù),然后把模型添加到tableView總數(shù)組 for (NSDictionary *appDict in appList) { AppModel *model=[[AppModel alloc]initWithDict:appDict]; [_dataArray addObject:model]; } //下載完數(shù)據(jù),更新了總數(shù)組,一定要刷新tableview!!! [_tableView reloadData];}
7、作業(yè)
scrollView滑動(dòng)
//第一步:初始化,從網(wǎng)絡(luò)接口下載數(shù)據(jù)-(void)createScrollView{ _allData1=[NSMutableArray array]; //陳奕迅網(wǎng)絡(luò)接口 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:)]; }//第二步:下載完成后觸發(fā)的方法,把下載好的data 存入總數(shù)組-(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];}//第三步:根據(jù)下載的總數(shù)組,改變ScrollView的contenSize 同時(shí)設(shè)置其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]; } //設(shè)置pageControl _pageControl.numberOfPages=_allData1.count; _pageControl.enabled=NO; [self.view bringSubviewToFront:_pageControl]; _pageControl.pageIndicatorTintColor=[UIColor redColor]; //啟動(dòng)定時(shí)器,讓scroView滑動(dòng) [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scrollViewMove) userInfo:nil repeats:YES];}//定時(shí)器觸發(fā)的方法-(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跟著移動(dòng)-(void)scrollViewDidScroll:(UIScrollView *)scrollView{ int page =scrollView.contentOffset.x/320; _pageControl.currentPage=page;}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注