IOS WKWebview 使用集锦

IOS WKWebview 和JS交互

1、删除WKWebview的缓存

WKWebView有默认的缓存功能,即便H5做了更改,app上显示的依旧是老得页面。为了解决这一问题,我们就会用到WKWebView的删除缓存功能。

iOS9 WKWebView新方法:


NSSet *websiteDataTypes = [NSSet setWithArray:@[
                        WKWebsiteDataTypeDiskCache,
                        WKWebsiteDataTypeOfflineWebApplicationCache,
                        WKWebsiteDataTypeMemoryCache,
                        WKWebsiteDataTypeLocalStorage,
                        WKWebsiteDataTypeCookies,
                        WKWebsiteDataTypeSessionStorage,
                        WKWebsiteDataTypeIndexedDBDatabases,
                        WKWebsiteDataTypeWebSQLDatabases
                    ]];
//你可以选择性的删除一些你需要删除的文件 or 也可以直接全部删除所有缓存的type  
//NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes   
modifiedSince:dateFrom completionHandler:^{
       // �code
    }];

在IOS7和8中,

NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,   
NSUserDomainMask, YES)[0];
NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]   
objectForKey:@"CFBundleIdentifier"];
NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
NSString *webKitFolderInCaches = [NSString   
stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
 NSString *webKitFolderInCachesfs = [NSString   
 stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];

NSError *error;
/* iOS8.0 WebView Cache的存放路径 */
[[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
[[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];

/* iOS7.0 WebView Cache的存放路径 */
[[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];

只要做一次清空缓存即可。

2、获取WKWebview的内容高度

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [_web_webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        //获取页面高度,并重置webview的frame
        double webViewHeight = [result doubleValue];
        CGRect frame = _web_webView.frame;
        frame.size.height = webViewHeight+15;
        _web_webView.frame = frame;
    }];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 24,054评论 8 183
  • 兴许是大学的暑假本就该是这样,一个表面上已经成年的大学生却根本无法过上一个自己动手丰衣足食的成年生活。我们这种闲散...
    穷不尽的日常阅读 546评论 1 3
  • 昨天,我在一个同学微信群里,听到以前的同事小刘老师在群里抱怨说:“大家有没有觉得,当老师真心好累啊?” 结果,他此...
    726fd54cb168阅读 572评论 0 0
  • 晚上和爸爸妈妈还有弟弟视频了一个半小时后,前面半个小时,和弟弟互动的比较多,后面的一个小时跟妈妈聊了很多,你妈妈对...
    叶子卷阅读 251评论 2 3