zoukankan      html  css  js  c++  java
  • 网络数据下载和JSON解析

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

    简介

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

      涉及到的知识点有:

      1.NSURLConnection异步下载和封装

      2.JSON格式和JSON格式解析

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

    内容

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

      什么是网络应用?

        对于iOS开发来说的网络应用,笔者觉得需要通过访问网络,获取服务端数据来实现全部功能的的iOS应用程序都可以成为网络应用。

      网络应用的程序结构

        网络应用程序的结构有B/S浏览器/服务器 , C/S客户端浏览器。C/S结构相对而言有更快的响应速度,因为他减少了必要的数据的传输,而且处理更多计算或逻辑处理。

      常见的网络接口形式

        iOS网络应用常见的数据接口一半都是HTTP形式的URL地址, 例如爱限免应用首页的数据地址为http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=

    在项目中一般使用一些开源库通过这种网址下载数据. 例如AFNetworking

        

      常见的数据格式

        常见的网络接口形式有XML,Json,我们现在讨论Json格式,在其他博文中会设计到 XML。

    2.NSURLConnection使用

      我们可以很方便的通过创建URL,  通过URL 创建链接来访问网络。下面提供几种获取网络数据的方法。

        // HTTP中使用URL地址
        //  http:// 地址使用协议(ftp://)
        //  iappfree.candou.com  主机地址(域名和IP)
        //  :8080                   主机端口
        //  /free/applications/limited  网页程序文件路径
        //  ?currency=rmb&page=1&category_id= 程序参数(参数用&分割)

      (1) 通过URL同步获取数据

    -(void)testNSStringDownloadData{
        
        NSURL *url = [NSURL URLWithString:@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=%d&category_id="];
        NSLog(@"%@",url);
        
        NSError * error = nil;
        NSString *content = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        
        if (error == nil) {
            NSLog(@"%@",content);
            
        }else{
        
            NSLog(@"下载失败");
        }
    }

      (2)通过NSURLConnection同步下载

    -(void)testNSURLConectionSynDownloadData{
        NSString *str = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=";
        
        NSURL * url = [NSURL URLWithString:str];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        NSError *error = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        if (error == nil) {
            NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"str = %@",string);
        }else{
            NSLog(@"failed");
        }
    }

      (3)更好的方式是通过NSURLConnection异步加载,在

    NSURLConnectionDataDelegate代理方法中实现数据下载完成的操作。
    @interface NLViewController () <NSURLConnectionDataDelegate>
    {
        NSURLConnection * _connection;
        NSMutableData * _data;
    }
    
    @end
    
    @implementation NLViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        //1. load data
        [self testNSURLConectionAsynDownloadData];
        
    }
    
    -(void)testNSURLConectionAsynDownloadData{
        NSString *urlString = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=";
        _data = [[NSMutableData alloc]init];
        
        //利用URL字符串初始化一个URL对象
        NSURL *url = [NSURL URLWithString:urlString];
        //使用URL创建一个NSURLRequest对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        // 初始化一个NSURLConnection对象,并立即开始访问数据,处理相应的代理方法。
        _connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
    }
    
    
    #pragma mark - 代理方法
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        NSLog(@"didReceiveResponse");
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        [_data appendData:data];
        NSLog(@"didReceiveData");
    }
    
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
        NSLog(@"connectionDidFinishLoading");
        NSString *str = [[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"dict = %@",dict);
        
        NSArray * dicts = [dict valueForKeyPath:@"applications"];
        for (NSDictionary *dict in dicts) {
            NSLog(@"name = %@",dict[@"name"]);
        }
    }

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

    JSON建构于两种结构:

    • “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 
    • 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

    4.Json解析

      可以通过系统提供的一个类NSJSONSerialization来完成,可以很方便的转为字典或者数组。范例代码如下。

    - (void)dealDownloadFinish:(NLHttpRequest *)request{
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray * dicts = [dict valueForKeyPath:@"list"];
        for (NSDictionary *dict in dicts) {
            NLEvent *event = [NLEvent eventWithDictionary:dict];
            [_modelArray addObject:event];
        }
        [_tableView reloadData];
    }
  • 相关阅读:
    文件上传---form表单,ajax,jquery,以及iframe无刷新上传 (processData,contentType讲解)
    原生ajax中get和post请求
    iframe伪造ajax
    python---xss(Cross Site Scripting)跨站脚本攻击和csrf(xsrf)跨站点请求伪造(Cross—Site Request Forgery)攻击
    python---session(最终版)__setitem__和__getitem__方法
    Android 设置横屏或竖屏
    Android 屏幕画笔实现
    实现android activity之间的跳转
    CustomViewWith_Image_Text_Video
    新闻客户端nices
  • 原文地址:https://www.cnblogs.com/wantyoulee/p/4384482.html
Copyright © 2011-2022 走看看