網(wǎng)絡(luò)緩存

#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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市茉贡,隨后出現(xiàn)的幾起案子窃蹋,更是在濱河造成了極大的恐慌,老刑警劉巖她君,帶你破解...
    沈念sama閱讀 206,723評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件脚作,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡缔刹,警方通過(guò)查閱死者的電腦和手機(jī)球涛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)校镐,“玉大人亿扁,你說(shuō)我怎么就攤上這事∧窭” “怎么了从祝?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,998評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)肝箱。 經(jīng)常有香客問(wèn)我哄褒,道長(zhǎng),這世上最難降的妖魔是什么煌张? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,323評(píng)論 1 279
  • 正文 為了忘掉前任呐赡,我火速辦了婚禮,結(jié)果婚禮上骏融,老公的妹妹穿的比我還像新娘链嘀。我一直安慰自己萌狂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,355評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布怀泊。 她就那樣靜靜地躺著茫藏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪霹琼。 梳的紋絲不亂的頭發(fā)上务傲,一...
    開(kāi)封第一講書(shū)人閱讀 49,079評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音枣申,去河邊找鬼售葡。 笑死,一個(gè)胖子當(dāng)著我的面吹牛忠藤,可吹牛的內(nèi)容都是我干的挟伙。 我是一名探鬼主播,決...
    沈念sama閱讀 38,389評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼模孩,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼尖阔!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起榨咐,我...
    開(kāi)封第一講書(shū)人閱讀 37,019評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤介却,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后祭芦,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體筷笨,經(jīng)...
    沈念sama閱讀 43,519評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,971評(píng)論 2 325
  • 正文 我和宋清朗相戀三年龟劲,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片轴或。...
    茶點(diǎn)故事閱讀 38,100評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡昌跌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出照雁,到底是詐尸還是另有隱情蚕愤,我是刑警寧澤,帶...
    沈念sama閱讀 33,738評(píng)論 4 324
  • 正文 年R本政府宣布饺蚊,位于F島的核電站萍诱,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏污呼。R本人自食惡果不足惜裕坊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,293評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望燕酷。 院中可真熱鬧籍凝,春花似錦周瞎、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,289評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至退盯,卻和暖如春彼乌,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背渊迁。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,517評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工慰照, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人宫纬。 一個(gè)月前我還...
    沈念sama閱讀 45,547評(píng)論 2 354
  • 正文 我出身青樓焚挠,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親漓骚。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蝌衔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,834評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容