.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void(^DataBlock)(NSData * data);
typedef void(^ImageSolveBlock)(UIImage *image);
@interface KX_NetTools : NSObject
//封装的旧方法
+(void)solveDataWithUrl:(NSString *)StringUrl
Method:(NSString *)method
HttpBody:(NSString *)StringBody
revokeBlock:(DataBlock)block;
//新方法
+(void)sslveDataWithUrl:(NSString *)StringUrl
Method:(NSString *)method
HttpBody:(NSString *)StringBody
revokeBlock:(DataBlock)block;
+ (void)SessionDownLoadWithUrl:(NSString *)stringUrl revokeBlock:(ImageSolveBlock)block;
@end
.m
#import "KX_NetTools.h"
@implementation KX_NetTools
+(void)solveDataWithUrl:(NSString *)StringUrl
Method:(NSString *)method
HttpBody:(NSString *)StringBody
revokeBlock:(DataBlock)block{
NSURL * url = [NSURL URLWithString:StringUrl];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
//将所有的字母转化成大写
NSString * SMethod = [method uppercaseString];
if ([@"POST" isEqualToString:SMethod]) {
[request setHTTPMethod:SMethod];
NSData * bodyData = [StringBody dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
}else if ([@"GET" isEqualToString:SMethod]){
}else{
@throw [NSException exceptionWithName:@"KX Param Error" reason:@"方法类型参数错误" userInfo:nil];
return;
}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
block(data);
}];
}
+ (void)SessionDownLoadWithUrl:(NSString *)stringUrl revokeBlock:(ImageSolveBlock)block{
//1.创建 url
NSURL * url = [NSURL URLWithString:stringUrl];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
//2.创建回话
NSURLSession *session = [NSURLSession sharedSession];
//3.创建任务
NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSData * ImageData = [NSData dataWithContentsOfURL:location];
UIImage * image = [UIImage imageWithData:ImageData];
//从子线程回到主线程进行界面更新
dispatch_async(dispatch_get_main_queue(), ^{
block(image);
});
}];
//启动
[task resume];
}