// 检查本地缓存
NSArray *arrayOfCache =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *cachesPath = [arrayOfCache objectAtIndex:0];
// 首页HTML缓存路径 static NSString *const HTML_CACHE_PATH = @"homeHtml.html";
NSString *HTMLCachePath = [cachesPath stringByAppendingPathComponent:HTML_CACHE_PATH];
//判断是否存在该路径
BOOL hasCache = [[NSFileManager defaultManager] fileExistsAtPath:HTMLCachePath];
if (hasCache) {
NSString *htmlStr = [[NSString alloc] initWithContentsOfFile:HTMLCachePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:htmlStr baseURL:nil];
// 判断缓存是否需要更新
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSTimeInterval lastDateInterval = [userDefault doubleForKey:HTML_CACHE_DATE_KEY];
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970] - lastDateInterval;
NSTimeInterval hourInterval = 60 * 60;
if (timeInterval > 2 * hourInterval) {
[self cacheHTMLFileWithCallBack:^(BOOL success) {
}];
}
}else {
// load request
NSString *urlStr = [kBaseH5 stringByAppendingString:@"/h5/appProject/appIndex/index.html"];
//urlStr = @"http://192.168.1.116/appProject/appIndex/index.html";
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
[self cacheHTMLFileWithCallBack:^(BOOL success) {
}];
}
- (void)cacheHTMLFileWithCallBack:(void(^)(BOOL success))callBack {
// load request
NSString *urlStr = [kBaseH5 stringByAppendingString:@"/h5/appProject/appIndex/index.html"];
//urlStr = @"http://192.168.1.116/appProject/appIndex/index.html";
NSURL *url = [NSURL URLWithString:urlStr];
dispatch_queue_t concurrentQueue = dispatch_queue_create("cocurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue, ^{
NSError *error = nil;
NSString *htmlStr = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSLog(@"下载成功");
NSArray *arrayOfCache =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *cachesPath = [arrayOfCache objectAtIndex:0];
NSString *HTMLCachePath = [cachesPath stringByAppendingPathComponent:HTML_CACHE_PATH];
NSError *error = nil;
[htmlStr writeToFile:HTMLCachePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setDouble:[[NSDate date] timeIntervalSince1970] forKey:HTML_CACHE_DATE_KEY];
callBack(YES);
}
}
});
}