Snail—iOS网络学习之得到网络上的数据

在开发项目project中,尤其是手机APP,一般都是先把界面给搭建出来。然后再从网上down数据 来填充

那么网上的数据是怎么得来的呢,网络上的数据无非就经常使用的两种JSON和XML

如今 大部分都是在用JSON

网络上数据传输都是以二进制形式进行传输的 ,仅仅要我们得到网上的二进制数据

假设它是JSON的二进制形式 那么我们就能够用JSON进行解析 假设是XML。那么我们能够用XML解析

关键是怎么得到网上的二进制数据呢

设计一个经常使用的工具类 非常easy 给我一个接口(URL),那我就能够用这个类得到二进制文件

新建了一个类WJJHttpReques 继承NSObject

以下是.h的代码

#import <Foundation/Foundation.h>

@interface WJJHttpRequest : NSObject

//请求的接口
@property (nonatomic,copy) NSString * httpUrl;
//网上下载的二进制文件
@property (nonatomic,strong) NSMutableData * data;
//代理
@property (nonatomic,strong) id delegate;
//代理的方法
@property (nonatomic,assign) SEL method;

//開始下载数据
- (void)start;
//断开连接
- (void)stop;

@end

#import "WJJHttpRequest.h"
#import "WJJRequestManager.h"

@interface WJJHttpRequest ()<NSURLConnectionDataDelegate>{
    //声明connection为全局变量
    NSURLConnection * _connection;
}

@end

@implementation WJJHttpRequest

//開始下载数据
- (void)start{
    NSURL * url = [NSURL URLWithString:self.httpUrl];
    NSURLRequest * request = [[NSURLRequest alloc] initWithURL:url];
    //仅仅要以下运行 那么代理方法就会运行了 然后開始从网上down数据
    _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

#pragma mark NSURLConnectionDataDelegate method
//收到server的响应调用的代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"收到server响应");
    if (self.data == nil) {
        self.data = [[NSMutableData alloc] init];
    }else{
        [self.data setLength:0];
    }
}

//接受server的二进制文件
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"接受到了server的二进制数据");
    [self.data appendData:data];
}

//假设成功了 參数就是YES 反之则是NO
- (void)loadFinished:(BOOL)success{
    if (!success) {
        [self.data setLength:0];
    }
    //检測要接收数据的回调对象 是否有method这种方法
    if ([self.delegate respondsToSelector:self.method]) {
        //假设有就运行这种方法 而且把自己当參数传过去
        [self.delegate performSelector:self.method withObject:self];
    }
    //这个是我自己设计的Request管理类 以下这句话的意思就是把 数据传给那些须要数据的地方后,把这个连接断开
    [[WJJRequestManager sharedManager] removeTask:self.httpUrl];
}

//接受数据完毕时调用的方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"数据接受完毕");
    [self loadFinished:YES];
}

//接收数据失败时调用的方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"数据请求失败");
    [self loadFinished:NO];
}

//停止下载数据
- (void)stop{
    if (_connection) {
        //取消连接
        [_connection cancel];
    }
    _connection = nil;
}

@end


原文地址:https://www.cnblogs.com/lxjshuju/p/6885721.html