1、獲取加載進度:
使用KOV來觀察
[webView addObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNew context:NULL];
2、獲取Title
[webView addObserver:selfforKeyPath:@"title"options:NSKeyValueObservingOptionNew context:NULL];
然后重寫KVO的實現方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == webView) {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
//加載進度
[progressView setAlpha:1.0f];
[progressView setProgress:webView.estimatedProgress animated:YES];
if(webView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[progressView setProgress:0.0f animated:NO];
}];
}
} else if ([keyPath isEqualToString:@"title"]) {
//頁面標題
self.title = webView.title;
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
3、返回某個歷史頁面
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if (navigationAction.navigationType==WKNavigationTypeBackForward) { //判斷是返回類型
if (webView.backForwardList.backList.count>0) { //得到棧里面的list
WKBackForwardListItem * item = webView.backForwardList.currentItem; //得到現在加載的list
for (WKBackForwardListItem * backItem inwebView.backForwardList.backList) { //循環遍歷,得到你想退出到
//添加判斷條件
[webView goToBackForwardListItem:[webView.backForwardList.backListfirstObject]];
}
}
}
//允許跳轉
decisionHandler(WKNavigationActionPolicyAllow);
}
4、清除緩存
- (void)deleteWebCache {
if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
//系統版本高于iOS9
NSSet *websiteDataTypes
= [NSSet setWithArray:@[
WKWebsiteDataTypeDiskCache,
WKWebsiteDataTypeMemoryCache,
]];
//// All kinds of data
//NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//// Date from
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
// Done
}];
} else {
//系統版本低于iOS9
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
NSError *errors;
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
}
}