#import <Foundation/Foundation.h>
#import "HttpRequestTool.h"
#define dispatch_async_main_queue(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
@interface HttpRequest : NSObject
+ (void)httpRequestStr:(NSString *)urlStr completion:(void (^)(NSData *data,NSURLResponse *response,NSError *error))completion;
+(void)postWithURL:(NSString *)urlStr pragram:(NSDictionary *)pragram completion:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completion;
/**
默認(rèn)緩存 (內(nèi)存4M袍睡,硬盤20M)
*/
+ (void)setDefaultCapacity;
/**
設(shè)置內(nèi)存緩存與硬盤緩存大小
@param memoryCapacity 內(nèi)存緩存大小
@param maxDiskCapactiy 硬盤緩存大小
*/
+ (void)setMaxMesmoryCapacity:(NSUInteger)memoryCapacity
maxDiskCapacity:(NSUInteger)maxDiskCapactiy;
/**
獲取緩存的大小
*/
+ (NSUInteger)getCacheCapacity;
/**
刪除指定位置的緩存
@param request 指定的緩存
*/
+ (void)removeCapacheCapacityRequest:(NSURLRequest *)request;
/**
刪除全部緩存
*/
+ (void)removeAllCapacheResquest;
/**
刪除指定時(shí)間的緩存
@param date 指定的時(shí)間
*/
+ (void)removeCacheResponseRequestSinceDate:(NSDate *)date;
/**
get請(qǐng)求
@param url 網(wǎng)絡(luò)url
@param paramgers 請(qǐng)求參數(shù) pragram
@param timeoutInterval 請(qǐng)求時(shí)間
@param cachPolicy 緩存策略
@param completionHandler 完成回調(diào)
@param errorHandler 錯(cuò)誤信息
*/
+ (void)getUrl:(NSString *)url
paramger:(id)paramgers
timeout:(NSTimeInterval)timeoutInterval
cachPolicy:(CJRequestCachePolicy)cachPolicy
completionHandler:(void(^)(NSData *data,NSURLResponse *response))completionHandler
errorHandeler:(void (^)(NSError *error))errorHandler;
/**
post請(qǐng)求
@param url 網(wǎng)絡(luò)URL
@param paramgers 請(qǐng)求參數(shù) NSDictionary
@param timeoutInterval 設(shè)置請(qǐng)求時(shí)間
@param cachPolicy 緩存策略
@param completionHandler 請(qǐng)求回調(diào)
@param errorHandler error
*/
+ (void)postUrl:(NSString *)url
paramger:(id)paramgers
timeout:(NSTimeInterval)timeoutInterval
cachPolicy:(CJRequestCachePolicy)cachPolicy
completionHandler:(void(^)(NSData *data,NSURLResponse *response))completionHandler
errorHandeler:(void (^)(NSError *error))errorHandler;
@end
#import "HttpRequest.h"
#import "YT_celvexiaoSettingVCViewController.h"
#import <UIKit/UIKit.h>
@implementation HttpRequest
//網(wǎng)絡(luò)加載
+ (void)httpRequestStr:(NSString *)urlStr completion:(void (^)(NSData *data,NSURLResponse *response,NSError *error))completion {
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
NSURLCache *cache = [NSURLCache sharedURLCache];
NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
if (response) {
NSLog(@"response-存在這個(gè)緩存%@",response);
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
completion (data , response, error);
});
}];
[dataTask resume];
}else {
NSLog(@"response-不存在這個(gè)緩存%@",response);
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
completion (data , response, error);
});
}];
[dataTask resume];
}
}
+(void)postWithURL:(NSString *)urlStr pragram:(NSDictionary *)pragram completion:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completion
{
// if (pragram == nil) {
// // 1:準(zhǔn)備一個(gè)作為接口調(diào)用參數(shù)的 字典
// NSMutableDictionary *pragram1 = [NSMutableDictionary dictionary];
// // 設(shè)置相關(guān)參數(shù)
// [pragram1 setObject:@1 forKey:@"appid"];
// [pragram1 setObject:@22.535868 forKey:@"latitude"];
// [pragram1 setObject:@113.950943 forKey:@"longitude"];
// [pragram1 setObject:@"BCCFFAAB6A7D79D1E6D1478F2B432B83CD451E2660F067BF" forKey:@"memberdes"];
// pragram = pragram1;
// }
// 1:解析參數(shù)
// NSString *pragmStr = [self dealWithPragram:pragram];
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:pragram options:NSJSONWritingPrettyPrinted error:nil];
// 2:創(chuàng)建URL 和 request
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3:設(shè)置相關(guān)請(qǐng)求
request.HTTPMethod = @"POST";
request.HTTPBody = bodyData;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Length"];
// [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// 4:發(fā)起請(qǐng)求
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//這個(gè)方法是 在子線程回調(diào),需要回到主線程
dispatch_async(dispatch_get_main_queue(), ^{
completion (data, response, error);
});
}];
[dataTask resume];
}
+ (NSString *)dealWithPragram:(NSDictionary *)pragram
{
NSArray *allkeys = [pragram allKeys];
NSMutableString *result = [NSMutableString string];
for (NSString *key in allkeys) {
[result appendString:[NSString stringWithFormat:@"%@=%@&",key , pragram[key]]];
}
return [result substringWithRange:(NSRange){0,result.length - 1}];
}
#pragma mark - Cache網(wǎng)絡(luò)請(qǐng)求
+ (void)setDefaultCapacity {
[HttpRequest setMaxMesmoryCapacity:4 maxDiskCapacity:20];
}
+ (void)setMaxMesmoryCapacity:(NSUInteger)memoryCapacity maxDiskCapacity:(NSUInteger)maxDiskCapactiy {
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity * 1024 * 1024 diskCapacity:maxDiskCapactiy * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:cache];
}
//硬盤緩存的大小
+ (NSUInteger)getCacheCapacity {
NSUInteger cacheCapacity = [[NSURLCache sharedURLCache] currentDiskUsage];
return cacheCapacity;
}
//移除指定緩存
+ (void)removeCapacheCapacityRequest:(NSURLRequest *)request {
@synchronized ([NSURLCache sharedURLCache]) {
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
}
}
//移除所有緩存
+ (void)removeAllCapacheResquest {
@synchronized ([NSURLCache sharedURLCache]) {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
//移除某段時(shí)間的緩存
+ (void)removeCacheResponseRequestSinceDate:(NSDate *)date {
@synchronized ([NSURLCache sharedURLCache]) {
[[NSURLCache sharedURLCache] removeCachedResponsesSinceDate:date];
}
}
//get請(qǐng)求
+ (void)getUrl:(NSString *)url paramger:(id)paramgers timeout:(NSTimeInterval)timeoutInterval cachPolicy:(CJRequestCachePolicy)cachPolicy completionHandler:(void (^)(NSData *, NSURLResponse *))completionHandler errorHandeler:(void (^)(NSError *))errorHandler {
NSMutableURLRequest *request = CJRequestWithURL(url, nil, paramgers, timeoutInterval, YES, cachPolicy);
if (request == nil || [request isEqual:[NSNull null]]) {
dispatch_async_main_queue(^{
NSError *error;
errorHandler(error);
});
return;
}
if (cachPolicy != CJRequestIgnoringLocalCacheData) {
NSCachedURLResponse *response = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (response != nil) { //判斷是否有緩存
NSLog(@"存在緩存");
}
}else {
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[HttpRequest removeCapacheCapacityRequest:request];
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if ((error == nil || [error isEqual:[NSNull null]])&& data != nil) {
dispatch_async_main_queue(^{
completionHandler(data,response);
});
if (cachPolicy == CJRequestIgnoringLocalCacheData) {
//忽略緩存沈撞,刪除緩存
[HttpRequest removeCapacheCapacityRequest:request];
}
}else { //緩存出錯(cuò),刪除緩存
dispatch_async_main_queue(^{
errorHandler(error);
});
[HttpRequest removeCapacheCapacityRequest:request];
}
}];
[task resume];
}
+ (void)postUrl:(NSString *)url paramger:(id)paramgers timeout:(NSTimeInterval)timeoutInterval cachPolicy:(CJRequestCachePolicy)cachPolicy completionHandler:(void (^)(NSData *, NSURLResponse *))completionHandler errorHandeler:(void (^)(NSError *))errorHandler {
NSMutableURLRequest *request = CJRequestWithURL(url, @"POST", paramgers, timeoutInterval, YES, CJRequestIgnoringLocalCacheData);
if (request == nil || [request isEqual:[NSNull null]]) {
dispatch_async_main_queue(^{
NSError *error;
errorHandler(error);
});
return;
}
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if ((error == nil || [error isEqual:[NSNull null]]) && data != nil) {
dispatch_async_main_queue(^{
completionHandler(data,response);
});
}else {
dispatch_async_main_queue(^{
errorHandler(error);
});
[HttpRequest removeCapacheCapacityRequest:request];
}
}];
[task resume];
}
@end