import <Foundation/Foundation.h>
typedef void (^completeBlock)(id result);
typedef void (^errorBlock)(NSError *error);
@interface NetworkRequest : NSObject
+(NetworkRequest *)shareInstance;
-(void)networkRequestWithUrlstr:(NSString *)urlStr requestType:(NSString *)requestType paramaterDic:(NSDictionary *)paramaterDic completeBlock:(completeBlock)completeBlock errorBlock:(errorBlock)errorBlock;
@end
/*************************/
import "NetworkRequest.h"
static NetworkRequest *netRequest = nil;
@implementation NetworkRequest
+(NetworkRequest *)shareInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
netRequest = [[NetworkRequest alloc]init];
});
return netRequest;
}
-(void)networkRequestWithUrlstr:(NSString *)urlStr requestType:(NSString *)requestType paramaterDic:(NSDictionary *)paramaterDic completeBlock:(completeBlock)completeBlock errorBlock:(errorBlock)errorBlock{
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
request.HTTPMethod = requestType;
request.HTTPBody = [self makeParamaterToDataWithDic:paramaterDic];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
completeBlock(result);
}else
{
errorBlock(error);
}
}];
[task resume];
}
- (NSData *)makeParamaterToDataWithDic:(NSDictionary *)dic{
NSString *paramateStr = [NSString string];
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *key in dic) {
[array addObject:[NSString stringWithFormat:@"%@=%@",key,dic[key]]];
}
paramateStr = [array componentsJoinedByString:@"&"];
NSData *data = [paramateStr dataUsingEncoding:NSUTF8StringEncoding];
return data;
}
@end