码迷,mamicode.com
首页 > 其他好文 > 详细

用Block封装网络请求

时间:2016-04-16 21:36:42      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

#import <Foundation/Foundation.h>

// 定义一个枚举
typedef NS_ENUM(NSInteger) {
    LY_GET,
    LY_POST
} URLRequestMethod;
///定义返回block网络请求结果
typedef void(^ResultBlock)(NSData *data,NSURLResponse *response,NSError *error);

@interface LYNetWorkRequestManager : NSObject

///网络请求的方法
+ (void)requestURL:(NSURL *)url RequestMethod:(URLRequestMethod)method Params:(NSDictionary *)param Result:(ResultBlock)resultBlock;

@end

 

#import "LYNetWorkRequestManager.h"

@implementation LYNetWorkRequestManager

///单例
+ (instancetype)defaultManager {
    static LYNetWorkRequestManager *manager = nil;
    @synchronized(self) {
        if (!manager) {
            manager = [[LYNetWorkRequestManager alloc]init];
        }
    }
    return manager;
}

///网络请求方式
+ (void)requestURL:(NSURL *)url RequestMethod:(URLRequestMethod)method Params:(NSDictionary *)param Result:(ResultBlock)resultBlock {
    // 定义一个空的可变字符串
    NSMutableString *urlString = [NSMutableString string];
    if ([url isKindOfClass:[NSURL class]]) {
        // 拼接url
        [urlString appendString:url.absoluteString];
    } else if ([url isKindOfClass:[NSString class]]) {
        [urlString appendString:(NSString *)url];
    }
    
    if (urlString.length == 0) {
        NSError *error = [NSError errorWithDomain:@"EPA" code:nil userInfo:@{@"reson:":@"网址输入错误"}];
        return;
    }
    // 把参数字典转换为字符串
    LYNetWorkRequestManager *manager = [LYNetWorkRequestManager new];
    NSString *paraStr = [manager strFromDic:param];
    
    // 判断请求类型
    switch (method) {
        case LY_GET:
        {
            if (paraStr.length > 0) {
                [urlString appendString:paraStr];
            }
            [manager getRequestURL:[NSURL URLWithString:urlString] resultBlock:resultBlock];
        }
            break;
        case LY_POST:
            [manager postRequestURL:urlString ParaStr:paraStr resultBlock:resultBlock];
            break;
            
        default:
            break;
    }
    
}
/// GET请求
- (void)getRequestURL:(NSURL *)url resultBlock:(ResultBlock)block {
    
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithURL:url completionHandler:block];
    //开始网络请求
    [dataTask resume];
}

/// POST请求
- (void)postRequestURL:(NSString *)urlStr ParaStr:(NSString *)paraStr resultBlock:(ResultBlock)block {
    
    //创建NSURL
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //创建可变请求
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    
    //请求体
    [mRequest setHTTPBody:[paraStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:mRequest completionHandler:block];
    [dataTask resume];
    
}

///把参数字典转换为字符串
- (NSString *)strFromDic:(NSDictionary *)dic {
    // 空数组
    NSMutableArray *mArray = [NSMutableArray array];
    
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [mArray addObject:str];
    }
    
    //数组拼接成字符串
    NSString *para = [mArray componentsJoinedByString:@"&"];
    
    return para;
}

@end

 调用封装的网络请求

[LYNetWorkRequestManager requestURL:[NSURL URLWithString:READLIST_URL] RequestMethod:LY_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {

  NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

  NSLog(@"%@",result);

  NSLog(@"%@",data);

  NSLog(@"%@",error);

}];

用Block封装网络请求

标签:

原文地址:http://www.cnblogs.com/asdfg/p/5399268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!