import <Foundation/Foundation.h>
一 聲明屬性和方法
// 請求數(shù)據(jù)成功之后進(jìn)行回調(diào) 返回NSData
typedef void(^Finish)(NSData *data);
// 請求數(shù)據(jù)失敗之后進(jìn)行回調(diào) 返回NSError
typedef void(^Error)(NSError *error);
// 請求方式的枚舉
typedef NS_ENUM(NSInteger,RequestType){
RequestGET,
RequestPOST
};
@interface RequestManager : NSObject
@property (nonatomic,copy)Finish finish;
@property (nonatomic,copy)Error error;
- (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;
import "RequestManager.h"
@implementation RequestManager
- (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{
RequestManager *request = [[RequestManager alloc]init];
[request requestWithUrlString:urlString requestType:requestType parDic:parDic finish:finish error:error];
}
-
(void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{
// 對block屬性進(jìn)行賦值
self.finish = finish;
self.error = error;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = 10;
// 如果是POST請求
if (requestType == RequestPOST) {
[request setHTTPMethod:@"POST"];if (parDic.count > 0) { [request setHTTPBody:[self parDicToPOSTData:parDic]]; }
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
self.error(error);
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
self.finish(data);
});
}
}];
// 調(diào)用此方法才是異步鏈接
[task resume];
}
- (NSData *)parDicToPOSTData:(NSDictionary *)parDic{
NSMutableArray *array = [NSMutableArray array];
for (NSString *key in parDic) {
NSString *string = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
[array addObject:string];
}
NSString *postString = [array componentsJoinedByString:@"&"];
return [postString dataUsingEncoding:NSUTF8StringEncoding];
}