美文网首页
网络缓存

网络缓存

作者: 豆豆阳光啊 | 来源:发表于2016-12-05 13:39 被阅读37次
    #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;
    
    /**
     默认缓存 (内存4M,硬盘20M)
     */
    + (void)setDefaultCapacity;
    
    /**
     设置内存缓存与硬盘缓存大小
    
     @param memoryCapacity  内存缓存大小
     @param maxDiskCapactiy 硬盘缓存大小
     */
    + (void)setMaxMesmoryCapacity:(NSUInteger)memoryCapacity
                  maxDiskCapacity:(NSUInteger)maxDiskCapactiy;
    
    /**
     获取缓存的大小
     */
    + (NSUInteger)getCacheCapacity;
    
    /**
     删除指定位置的缓存
     @param request 指定的缓存
     */
    + (void)removeCapacheCapacityRequest:(NSURLRequest *)request;
    
    /**
     删除全部缓存
     */
    + (void)removeAllCapacheResquest;
    
    /**
     删除指定时间的缓存
    
     @param date 指定的时间
     */
    + (void)removeCacheResponseRequestSinceDate:(NSDate *)date;
    
    /**
     get请求
    
     @param url               网络url
     @param paramgers         请求参数  pragram
     @param timeoutInterval   请求时间
     @param cachPolicy        缓存策略
     @param completionHandler 完成回调
     @param errorHandler      错误信息
     */
    + (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请求
    
     @param url               网络URL
     @param paramgers         请求参数 NSDictionary
     @param timeoutInterval   设置请求时间
     @param cachPolicy        缓存策略
     @param completionHandler 请求回调
     @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
    //网络加载
    + (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-存在这个缓存%@",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-不存在这个缓存%@",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:准备一个作为接口调用参数的 字典
    //        NSMutableDictionary *pragram1 = [NSMutableDictionary dictionary];
    //        //    设置相关参数
    //        [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:解析参数
    //    NSString *pragmStr = [self dealWithPragram:pragram];
        NSData *bodyData = [NSJSONSerialization dataWithJSONObject:pragram options:NSJSONWritingPrettyPrinted error:nil];
        //    2:创建URL 和 request
        NSURL *url = [NSURL URLWithString:urlStr];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        //    3:设置相关请求
        
        request.HTTPMethod = @"POST";
        
        request.HTTPBody = bodyData;
        
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Length"];
        
    //    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
        //    4:发起请求
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        
        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];
        
    }
    
    + (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网络请求
    + (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];
        }
    }
    
    //移除某段时间的缓存
    + (void)removeCacheResponseRequestSinceDate:(NSDate *)date {
        @synchronized ([NSURLCache sharedURLCache]) {
            [[NSURLCache sharedURLCache] removeCachedResponsesSinceDate:date];
        }
    }
    
    //get请求
    + (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 {     //缓存出错,删除缓存
                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
    

    相关文章

      网友评论

          本文标题:网络缓存

          本文链接:https://www.haomeiwen.com/subject/htwkmttx.html