app 缓存html页面,APP给HTML做缓存

// 检查本地缓存

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);

}

}

});

}

c24a8bd8f49f

Snip20170712_1.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值