A-A+

iOS-WKWebView缓存并保证实时性

博客主机

说到WKWebView的缓存,我之前也写过一篇关于UIWebView的缓存的,文章地址如下:

《iOS-UIWebview缓存并保证实时性》

但是这个方法对于WKWebView就失去了效果,后来公司的项目全部改为WKWebView,至于WKWebView的好处,这边就不过多叙述了;上面的方法要是在WKWebView上就失效了,后来我也修改了新的方案,自己的闲暇时间一直在维护自己的几款软件ZFJObsLibZFJPyMix,所以一直没时间总结优化一下,在此我对ZFJCacheProtocol重新优化了一下,大家也可以根据自己的理解和需求自行优化设计;在UIWebView的时候我是缓存全部数据的,在这里开发者可以自行选择缓存的类型!

具体流程图如下:

如果想详细了解NSURLRequest的相关的缓存机制,可以看《iOS-UIWebview缓存并保证实时性》

详细API如下:

使用教程

只需要在需要监听的页面开启网络监听就可以了,在不需要监听的时候取消监听即可,如下:

- (void)viewWillAppear:(BOOL)animated {
    

[super viewWillAppear:animated]

;     //开始监听缓存数据     [ZFJCacheProtocol startMonitorRequest:ZFJCacheAllType]; } - (void)viewWillDisappear:(BOOL)animated {     

[super viewWillDisappear:animated]

;     //在不需要用到webview的时候即使的取消监听     [ZFJCacheProtocol cancelMonitorRequest]; }复制代码

自定义配置

1.自定义缓存类型

ZFJWebCache主要根据MIMEType可以对缓存的数据类型进行区分,具体指出的缓存类型如下:

typedef NS_ENUM(NSInteger, ZFJCacheType) {
    ZFJCacheAllType         = 1 << 0,     //缓存全部
    ZFJCacheImageType       = 1 << 1,     //缓存图片
    ZFJCacheVideoType       = 1 << 2,     //缓存视频
    ZFJCacheAudioType       = 1 << 3,     //缓存音频
    ZFJCacheTextType        = 1 << 4,     //缓存text
    ZFJCacheMessageType     = 1 << 5,     //缓存message
    ZFJCacheX_WorldType     = 1 << 6,     //缓存x-world
    ZFJCacheApplicationType = 1 << 7,     //缓存application
    ZFJCacheNoneType        = 1 << 8,     //未知类型
};

比如你只想缓存image使用如下:

- (void)viewWillAppear:(BOOL)animated {
    

[super viewWillAppear:animated]

;     //开始监听缓存数据     [ZFJCacheProtocol startMonitorRequest:ZFJCacheImageType]; }复制代码

2.设置缓存过期时间

ZFJWebCache的默认过期时间是一小时(3600s),如果想自定义缓存过期时间可设置如下:

// 设置缓存过期时间
    [ZFJCacheConfig instance].updateInterval = 1200;

3.设置忽略url

NSArray *ignoreUrlArray = @[@"http://www.baidu.com"];
[ZFJCacheConfig instance].ignoreUrlArray = ignoreUrlArray;

4.其他配置API如下

//
//  ZFJCacheConfig.h
//  Ahaschool
//
//  Created by ZFJMBPro on 2020/1/13.
//  Copyright © 2020 ahaschool. All rights reserved.
//

#import#import "ZFJMIMEType.h"

@interface ZFJCacheConfig : NSObject

+ (instancetype)instance;

/// 上一次url请求时间
@property (readwrite, nonatomic, strong) NSDictionary *lastRequestDict;

/// 支持的缓存类型
@property (nonatomic,assign) ZFJCacheType cacheType;

/// 相同的Url请求缓存时间间隔(默认3600s)
@property (readwrite, nonatomic, assign) NSInteger updateInterval;

/// 为NSURLSession配置一些请求所需要的策略
@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *config;

/// 请求任务队列
@property (readwrite, nonatomic, strong) NSOperationQueue *forgeroundNetQueue;

/// 缓存任务队列
@property (readwrite, nonatomic, strong) NSOperationQueue *backgroundNetQueue;

/// 忽略的url链接
@property (nonatomic, strong) NSArray *ignoreUrlArray;

/// 清空内存中的url记录(收到内存警告的时候可以调用这个方法清空内存中的url记录)
- (void)clearUrlDict;

/// 获取缓存路径
- (NSString *)documentPath;

/// 是否支持缓存
- (BOOL)isSupportCache:(NSString *)mimeType;

@end

源码

GTIEE:https://gitee.com/zfj1128/ZFJWebCache

给我留言

Copyright © ios教程,苹果粉丝,苹果资讯,ios入门教程,ios学习,ios程序员,ios视频教程,ios粉丝网 保留所有权利.   Theme  Ality

用户登录