43.用Block和协议对网络请求简单封装

MainViewController.m文件

#import "MainViewController.h"
#import "NetWorkingDelegate.h"
#import "NetWorkingTool.h"
@interface MainViewController ()<NetWorkingDelegate>
@end
@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self blockData];
    [self delegateData];
}
- (void)blockData
{
    // 1.调用实例方法请求数据,先创建一个工具类的实例对象
    NetWorkingTool *tool = [[NetWorkingTool alloc] init];
    [tool netWorkingWithURL: @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295"block:^(id result) {
        //现在我们所解析的数据就是result,在这里进行数据处理
        NSMutableDictionary *dic = result;
        NSLog(@"%@",dic);
    }];
    // 2.调用类方法请求数据,不需要创建对象
    [NetWorkingTool netWorkingWithURl:@"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295" back:^(id result) {
        NSMutableDictionary *dic = result;
        NSLog(@"%@",dic);
    }];
    // 3.调用类方法请求数据,不需要创建对象(POST请求)
    [NetWorkingTool netWorkingWithURL:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" bodyStr:@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213" back:^(id result) {
        NSLog(@"%@",result);
    }];
}

- (void)delegateData
{
    // 1.调用实例方法请求数据  所以要用对象来调用   所以当前我们要创建网络工程类的对象
    NetWorkingDelegate *tool = [[NetWorkingDelegate alloc] init];
    tool.delegate = self;
    [tool netWorkingWithURL:@"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295"];
    // 2.使用加号方法来进行网络请求
    [NetWorkingDelegate netWorkingWithURL:@"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295" delegate:self];
 }
- (void)getData:(id)result
{
    NSMutableDictionary *dic = result;
    NSLog(@"%@",dic);
}
@end

利用Block封装: NetWorkingTool文件

#import <Foundation/Foundation.h>
#pragma mark 这个类就通过block的方法,把这个类请求的数据返回到视图控制器
typedef void (^Block)(id result);
@interface NetWorkingTool : NSObject

- (void)netWorkingWithURL:(NSString *)strURL block:(Block)block;
//这个叫参数形容词back  这个名字不一样没事
+ (void)netWorkingWithURl:(NSString *)strURL back:(Block)block;
//实现POST请求
+ (void)netWorkingWithURL:(NSString *)strURL bodyStr:(NSString *)bodyStr back:(Block)block;
@end
#import "NetWorkingTool.h"
@implementation NetWorkingTool
- (void)netWorkingWithURL:(NSString *)strURL block:(Block)block
{
    NSString *strEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strEncode];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        //把json处理好的数据,通过block进行回调,返回到视图控制器
        block(result);
    }];
}

+ (void)netWorkingWithURl:(NSString *)strURL back:(Block)block
{
    NSString *strEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strEncode];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        block(result);
    }];
}

+ (void)netWorkingWithURL:(NSString *)strURL bodyStr:(NSString *)bodyStr back:(Block)block
{
    NSString *str = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        block(result);
    }];
}
@end

利用协议封装: NetWorkingDelegate文件

#import <Foundation/Foundation.h>
//声明一份协议
@protocol NetWorkingDelegate <NSObject>
- (void)getData:(id)result;
@end

@interface NetWorkingDelegate : NSObject
//设置代理人的属性
@property (nonatomic, assign)id<NetWorkingDelegate>delegate;
- (void)netWorkingWithURL:(NSString *)strURL;
+ (void)netWorkingWithURL:(NSString *)strURL delegate:(id<NetWorkingDelegate>)delegate;
@end
#import "NetWorkingDelegate.h"
@implementation NetWorkingDelegate
- (void)netWorkingWithURL:(NSString *)strURL
{
    //因为无法保证网址没有中文,所以需要先对传过来的字符串进行转换
    NSString *strEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //创建一个NSURL
    NSURL *url = [NSURL URLWithString:strEncode];
    //创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //用block实现异步
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //对数据进行json解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        //对已经创建好的数据通过协议的方法带到VC里
        [self.delegate getData:result];
    }];
}

+ (void)netWorkingWithURL:(NSString *)strURL delegate:(id<NetWorkingDelegate>)delegate
{
    NSString *str = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //对数据进行json解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        //对已经创建好的数据通过协议的方法带到VC里
        [delegate getData:result];
    }];
}
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值