在开发项目工程中,尤其是手机APP,一般都是先把界面给搭建出来,然后再从网上down数据 来填充
那么网上的数据是怎么得来的呢,网络上的数据无非就常用的两种JSON和XML
现在 大部分都是在用JSON
网络上传输数据都是以二进制形式进行传输的 ,只要我们得到网上的二进制数据
如果它是JSON的二进制形式 那么我们就可以用JSON进行解析 如果是XML,那么我们可以用XML解析
关键是怎么得到网上的二进制数据呢
设计一个常用的工具类 很简单 给我一个接口(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
//收到服务器的响应调用的代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"收到服务器响应");
if (self.data == nil) {
self.data = [[NSMutableData alloc] init];
}else{
[self.data setLength:0];
}
}
//接受服务器的二进制文件
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"接受到了服务器的二进制数据");
[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