typedef void(^Block)(id result);
typedef NS_ENUM(NSInteger, MethodType) {
GETType,
POSTType,
};
@protocol NetworkingToolDelegate <NSObject>
- (void)bringResult:(id)result;
@end
@interface NetworkingTool : NSObject
+ (void)networkingWithStrURL:(NSString *)strURL deledate:(id<NetworkingToolDelegate>)delegate;
+ (void)networkingWithStrURL:(NSString *)strURL type:(MethodType)type bodyStr:(NSString *)bodyStr block:(Block)block;
@end
// 都是加号方法(类方法,类直接调用)
+ (void)networkingWithStrURL:(NSString *)strURL deledate:(id<NetworkingToolDelegate>)delegate{
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// 代理人执行协议方法
[delegate bringResult:result];
});
}];
[task resume];
}
+ (void)networkingWithStrURL:(NSString *)strURL type:(MethodType)type bodyStr:(NSString *)bodyStr block:(Block)block {
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if (type == POSTType) {
[request setHTTPMethod:@"POST"];
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// 将result传出去
block(result);
}];
[task resume];
}