WKWebView离线缓存

本文介绍了在不考虑缓存失效或过期的情况下,如何实现WKWebView的离线缓存功能。主要包括三步:1)配置NSURLCache;2)初始化并加载网页;3)首次加载成功后的本地存储操作。

只需要离线缓存,而不考虑是否失效或过期的情况下(很少不考虑),可以直接进行本地存储和加载

1.NSURLCache设置

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024 * 1024
                                                         diskCapacity:1024 * 1024 * 1024
                                                             diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    return YES;
}

2.初始化加载

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _wkWeb = [[WKWebView alloc]initWithFrame:self.view.bounds];
    _wkWeb.UIDelegate = self;
    _wkWeb.navigationDelegate = self;
    [self.view addSubview:_wkWeb];
    
    _url = @"http://www.baidu.com";
    
    NSURL *URL = [NSURL URLWithString:_url];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
    NSURLCache *cache = [NSURLCache sharedURLCache];
    NSCachedURLResponse *cacheResponse = [cache cachedResponseForRequest:request];
    if (!cacheResponse) {
        [_wkWeb loadRequest:request];
    }else{

        [self.wkWeb loadData:cacheResponse.data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:request.URL];
    }
}

3.首次加载成功之后的存储

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    NSURLCache *cache = [NSURLCache sharedURLCache];
    
    NSURL *url = [NSURL URLWithString:_url];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
    
    NSCachedURLResponse *cacheResponse = [cache cachedResponseForRequest:request];
    if (!cacheResponse) {
        NSData *dataContent = [NSData dataWithContentsOfURL:url];
        NSURLResponse *response = [[NSURLResponse alloc]initWithURL:url MIMEType:@"text/html" expectedContentLength:0 textEncodingName:@"UTF-8"];
        
        cacheResponse = [[NSCachedURLResponse alloc]initWithResponse:response data:dataContent];
        [cache storeCachedResponse:cacheResponse forRequest:request];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值