封装网络请求

我们都知道协议代理,懂得如何去使用系统或者第三方的协议代理,

知道使用的步骤:

1.创建对象并设置代理

2.遵循协议

3.实现协议中的方法

 

但不知道你们有没有自己去封装过协议代理,知不知道内部是如何封装的?

 

接下来,我用一个网络请求的例子来进行一次简单的封装,深入理解下封装的内涵。

 

1.创建一个继承自NSObject的DDZHttpRequest类

 

定义头文件(.h)

#import <Foundation/Foundation.h>

//定义网络请求协议
@protocol DDZHttpRequestDelegate <NSObject>

//协议中定义一个下载数据的请求方法
- (void)getDownloadDataWithHttpRequest:(id)httpRequest;

@end

@interface DDZHttpRequest : NSObject <NSURLConnectionDataDelegate>

/** 数据 */
@property (nonatomic,strong) NSMutableData *data;

/** 持有协议的id指针(用于保存传过来的delegate对象) */
@property (nonatomic,assign) id<DDZHttpRequestDelegate> delegate;

//构造方法
- (id)initWithHttpRequest:(NSString *)requestPath andDelegate:(id)delegate;

@end

 

 

实现文件(.m)

#import "DDZHttpRequest.h"

@implementation DDZHttpRequest

- (id)initWithHttpRequest:(NSString *)requestPath andDelegate:(id)delegate {
    if (self = [super init]) {
        //进行封装对NSURLConnection进行封装
        
        //创建URL对象
        NSURL *url = [NSURL URLWithString:requestPath];
        //保留(记录)外面传过来的delegate
        self.delegate = delegate;
        
        //发送异步请求
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
        
        
    }
    
    return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"开始请求");
    _data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"请求过程中");
    [_data appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"结束");
    //持有协议的id指针,可以使用协议中的方法
    //self:是DDZHttpRequest的当前对象 记住:只要self在哪个类里就是哪个类的当前对象
    [self.delegate getDownloadDataWithHttpRequest:self];
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%@",error);
}


@end

 

在构造方法中,我们将传进来的delegate进行保留,用于数据请求结束时,使传进来的对象调用协议方法,并将数据data也传出去。

这样我们的封装就大功告成了!

 

2.在ViewController文件中,

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    DDZHttpRequest *httpRequest = [[DDZHttpRequest alloc] initWithHttpRequest:@"http://api.budejie.com/api/api_open.php?a=tags_list&c=subscribe" andDelegate:self];
    
}

/*
 调用的开发者:
 1.创建对象并设置代理
 2.遵循协议
 3.实现协议中的方法
 */

- (void)getDownloadDataWithHttpRequest:(id)httpRequest {
    
    DDZHttpRequest *request = httpRequest;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:request.data options:NSJSONReadingMutableContainers error:nil];
    
    NSLog(@"%@",dic);
}

 

运行之后,就会在控制台上打印出请求回来的数据。

posted @ 2016-06-20 19:54  blue-fly  阅读(405)  评论(0编辑  收藏  举报