IOS之网络数据下载和JSON解析

IOS之网络数据下载和JSON解析

简介

  在本文中笔者将要给大家介绍IOS中如何利用NSURLConnection从网络上下载数据,以及如何解析下载下来的JSON数据格式,以及如何显示数据和图片的异步下载显示

   涉及到的知识点有:

        1.NSURLConnection异步下载和封装;

        2.JSON格式和JSON格式解析;

        3.数据显示和使用SDWebImage异步显示图片。

内容

  1.网络下载基础知识介绍

      什么是网络应用?

       网络应用的程序结构

       常见的网络接口形式

       常见的数据格式

      界面开发的一般流程

  2 NSURLConnection使用

#import "ZJHttpRequest.h"
//消除performSelector的警告
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
//类扩展
//项目实践:
//有些实例变量内部使用,不想放在头文件中,就放在这儿
@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 ];
    }
}
@end

  3. JSON格式说明和格式化工具

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    数据接口
       NSString*urlString=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=";

    
    _dataArray=[[NSMutableArray alloc]init];
    
    //    下载
    _request = [[ZJHttpRequest alloc]init];
    [_request requestWithUrl:urlString target:self action:@selector(dealDownloadFinish:)];
    
    [self creatTableView];
    
}

-(void)creatTableView
{

    _tableview=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    [self.view addSubview:_tableview];


}
-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;

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

   AppModel*model=_dataArray[indexPath.row];
//    cell.textLabel.text= model.name;
    cell.nameLabel.text=model.name;
  
//    从网络中加载图片
    [cell.iconImageView setImageWithURL:[NSURL URLWithString:model.iconUrl]];
    return cell;

}
-(void)dealDownloadFinish:(ZJHttpRequest*)request
{
    NSDictionary*dic=[NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"dic= %@",dic);
    NSArray *appList=dic[@"applications"];
    for (NSDictionary*appDict in appList) {
        AppModel*model=[[AppModel alloc]init];
        model.applicationId=appDict[@"application"];
        model.name=appDict[@"name"];
        model.iconUrl=appDict[@"iconUrl"];
        [_dataArray addObject:model];
        
    }
//    下载数据刷新显示
    [_tableview reloadData];
}

   4.一个完成页面点实现(包括model的创建,SDWebImage 的使用)

效果图

 

一,将字符串转换为NSURL 的对象

//把字符串的Url封装成NSURL 对象

    NSURL * url = [NSURL URLWithString:@"http://www.7160.com//uploads/allimg/140919/9-140919104223.jpg"];

    

//    服务器:Java ,C#  PHP

//    服务器返回的信息包括图片视屏音频等都是二进制的(NSData)

二,同步下载

//    接受二进制

    NSData * imageData = [NSData dataWithContentsOfURL:url];

    NSLog(@"接收到的图片:%@",imageData);

    

    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 320,200)];

    [self.view addSubview:imageView];

    imageView.image = [UIImage imageWithData:imageData];

三:NSURLRequest和NSMutableURLRequest

1,二者为继承关系

NSURLRequest不可变的请求对象 请求的url  

NSMutableURLRequest 可变的请求对象

不可变的请求对象一旦创建,url  请求超时的时间都不能更改

2 初始化一个请求对象

//创建一个不可变的请求对象,用一个Url初始化

    NSURLRequest * request = [NSURLRequest requestWithURL:url];

//创建一个不可变的请求对象,并且在创建的时候指定url 的缓存方式和超时时间

  NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

//    创建一个可变的请求对象

    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];

    [request setURL:url];

    [request setTimeoutInterval:10];

三  NSURLConnection

用下属两种方式初始化异步请求对象,会立即开始请求

1,

//当收到connectionWithRequest: delegate: 类方法时,下载会立即开始,在代理(delegate)

//收到connectionDidFinishLoading:或者connection:didFailWithError:消息之前

//可以通过给连接发送一个cancel:消息来中断下载

2,

//    [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]

//如果没有立即开始请求,如果需要开始请求的时候可以调用 start 方法开开始请求

3,

 NSURLConnection * con = [[NSURLConnection alloc] initWithRequest:request delegate:self];

4,代理方法

//当请求接收发哦服务器的响应的时候执行该代理方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    

//    获取文件大小

    allSize = [response expectedContentLength];

//    获取文件类型

   NSString * string = [response MIMEType];

//    获取文件名

   NSString * string1 = [response suggestedFilename];

    

    NSLog(@"已经接收到服务器响应 %@",string1);

}

//当接收到服务端的数据的时候执行该代理方法

//可能会多次调用

//追加数据

//计算下载速度

//和下载进度

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

//     追加数据

    [downLoadData appendData:data];

//    计算下载进度(进度=已经下载的数据的大小/总的数据大小)

 }

//下载完成执行该方法

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

//    替换图片

    

    _downloadImage.image = [UIImage imageWithData:downLoadData];

    [activ stopAnimating];

    

}

//链接失败执行该方法

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

      

}

四,json 数据解析

//    NSJSONSerialization利用该类可以将JSON 数据转换为foundation 的对象字典和数组

 NSMutableDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:downloadData options:NSJSONReadingMutableLeaves error:nil];

//NSJSONReadingMutableContainers: 设置此参加那返回的对象是可以随时添加新的值,也就是 Mutable 类型的对象

//NSJSONReadingMutableLeaves: 还不知道

//NSJSONReadingAllowFragments:设置此参数那返回对象是不能再去动态修改的, 如:NSArray NSDictionary

//    遇到{} 用字典接收

//    遇到[]用数组接收

原文地址:https://www.cnblogs.com/JeinoZT/p/4384519.html