NSURLCache,iOS

来源:互联网 发布:mac装win8.1 编辑:程序博客网 时间:2024/05/22 05:34

1.在didFinishLaunchingWithOptions添加初始化缓存方法。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    CustomURLCache *urlCache = [[CustomURLCachealloc] initWithMemoryCapacity:20 *1024 * 1024

                                                                 diskCapacity:200 * 1024 * 1024

                                                                     diskPath:nil

                                                                    cacheTime:0];

    [CustomURLCachesetSharedURLCache:urlCache];


2.处理缓存request和response的方法

- (NSString *)cacheFolder;

- (NSString *)cacheFilePath:(NSString *)file;

- (NSString *)cacheRequestFileName:(NSString *)requestUrl;

- (NSString *)cacheRequestOtherInfoFileName:(NSString *)requestUrl;

- (NSCachedURLResponse *)dataFromRequest:(NSURLRequest *)request;

- (void)deleteCacheFolder;


@end


@implementation CustomURLCache


@synthesize cacheTime = _cacheTime;

@synthesize diskPath = _diskPath;

@synthesize responseDictionary = _responseDictionary;


- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path cacheTime:(NSInteger)cacheTime {

    if (self = [selfinitWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path]) {

        self.cacheTime = cacheTime;

        if (path)

            self.diskPath = path;

        else

            self.diskPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject];

        

        self.responseDictionary = [NSMutableDictionarydictionaryWithCapacity:0];

    }

    return self;

}


- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {

    if ([request.HTTPMethodcompare:@"GET"] !=NSOrderedSame) {

        return [supercachedResponseForRequest:request];

    }

    

    return [selfdataFromRequest:request];

}


- (void)removeAllCachedResponses {

    [superremoveAllCachedResponses];

    

    [selfdeleteCacheFolder];

}


- (void)removeCachedResponseForRequest:(NSURLRequest *)request {

    [superremoveCachedResponseForRequest:request];

    

    NSString *url = request.URL.absoluteString;

    NSString *fileName = [selfcacheRequestFileName:url];

    NSString *otherInfoFileName = [selfcacheRequestOtherInfoFileName:url];

    NSString *filePath = [selfcacheFilePath:fileName];

    NSString *otherInfoPath = [selfcacheFilePath:otherInfoFileName];

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

    [fileManager removeItemAtPath:filePath error:nil];

    [fileManager removeItemAtPath:otherInfoPatherror:nil];

}


#pragma mark - custom url cache


- (NSString *)cacheFolder {

    return@"URLCACHE";

}


- (void)deleteCacheFolder {

    NSString *path = [NSStringstringWithFormat:@"%@/%@",self.diskPath, [selfcacheFolder]];

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

    [fileManager removeItemAtPath:path error:nil];

}


- (NSString *)cacheFilePath:(NSString *)file {

    NSString *path = [NSStringstringWithFormat:@"%@/%@",self.diskPath, [selfcacheFolder]];

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

    BOOL isDir;

    if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {

        

    } else {

        [fileManager createDirectoryAtPath:pathwithIntermediateDirectories:YESattributes:nilerror:nil];

    }

    return [NSStringstringWithFormat:@"%@/%@", path, file];

}


- (NSString *)cacheRequestFileName:(NSString *)requestUrl {

    return [CacheUtilmd5Hash:requestUrl];

}


- (NSString *)cacheRequestOtherInfoFileName:(NSString *)requestUrl {

    return [CacheUtilmd5Hash:[NSStringstringWithFormat:@"%@-otherInfo", requestUrl]];

}


- (NSCachedURLResponse *)dataFromRequest:(NSURLRequest *)request {

    NSString *url = request.URL.absoluteString;

    NSString *fileName = [selfcacheRequestFileName:url];

    NSString *otherInfoFileName = [selfcacheRequestOtherInfoFileName:url];

    NSString *filePath = [selfcacheFilePath:fileName];

    NSString *otherInfoPath = [selfcacheFilePath:otherInfoFileName];

    NSDate *date = [NSDatedate];

    

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

    if ([fileManager fileExistsAtPath:filePath]) {

        BOOL expire = false;

        NSDictionary *otherInfo = [NSDictionarydictionaryWithContentsOfFile:otherInfoPath];

        

        if (self.cacheTime >0) {

            NSInteger createTime = [[otherInfoobjectForKey:@"time"]intValue];

            if (createTime + self.cacheTime < [date timeIntervalSince1970]) {

                expire = true;

            }

        }

        

        if (expire == false) {

            if (![ReachabilitynetworkAvailable]) {

                NSLog(@"data from cache ...");

                NSData *data = [NSDatadataWithContentsOfFile:filePath];

                NSURLResponse *response = [[NSURLResponsealloc] initWithURL:request.URL

                                                                    MIMEType:[otherInfo objectForKey:@"MIMEType"]

                                                       expectedContentLength:data.length

                                                            textEncodingName:[otherInfo objectForKey:@"textEncodingName"]];

                NSCachedURLResponse *cachedResponse = [[NSCachedURLResponsealloc] initWithResponse:responsedata:data] ;

                //            [response release];

                return cachedResponse;

            }

        } else {

            NSLog(@"cache expire ... ");

            [fileManager removeItemAtPath:filePatherror:nil];

            [fileManager removeItemAtPath:otherInfoPatherror:nil];

        }

    }

    if (![ReachabilitynetworkAvailable]) {

        return nil;

    }

    __block NSCachedURLResponse *cachedResponse =nil;

    //sendSynchronousRequest请求也要经过NSURLCache

    id boolExsite = [self.responseDictionaryobjectForKey:url];

    if (boolExsite == nil) {

        [self.responseDictionarysetValue:[NSNumbernumberWithBool:TRUE]forKey:url];

        

        [NSURLConnectionsendAsynchronousRequest:request queue:[[NSOperationQueuealloc] init]completionHandler:^(NSURLResponse *response,NSData *data,NSError *error)

         {

             if (response && data) {

                 

                 [self.responseDictionaryremoveObjectForKey:url];

                 

                 if (error) {

                     NSLog(@"error : %@", error);

                     NSLog(@"not cached: %@", request.URL.absoluteString);

                     cachedResponse = nil;

                 }

                 if ([ReachabilitynetworkAvailable]) {

                     NSLog(@"cache url --- %@ ",url);

                     

                     //save to cache

                     NSDictionary *dict = [NSDictionarydictionaryWithObjectsAndKeys:[NSStringstringWithFormat:@"%f", [datetimeIntervalSince1970]], @"time",

                                           response.MIMEType,@"MIMEType",

                                           response.textEncodingName,@"textEncodingName", nil];

                     [dict writeToFile:otherInfoPathatomically:YES];

                     [data writeToFile:filePathatomically:YES];

                     

                     cachedResponse = [[NSCachedURLResponsealloc] initWithResponse:responsedata:data];

                 }

             }

             

         }];

        

        return cachedResponse;

        //NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        

        

    }

    return nil;

}




0 0