·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 4_1网络学习第一天后感--网络数据下载

4_1网络学习第一天后感--网络数据下载

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

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;
}