IOS WKWebView--清除缓存、弹窗处理


转自:http://www.brighttj.com/ios/ios-wkwebview-new-features-and-use.html


在UIWebView下,可以使用

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. [[NSURLCache sharedURLCache] removeAllCachedResponses];//清除缓存  

来实现清除缓存,但当替换使用WKWebView后,这个方法并不生效了(据说WKWebView不支持,我没找到官方说法~)

不过寻找了一下解决方法,分享一下

--------------IOS9以上----------------

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];  
  2.     [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]  
  3.                      completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {  
  4.                          for (WKWebsiteDataRecord *record  in records)  
  5.                          {  
  6. //                             if ( [record.displayName containsString:@"baidu"]) //取消备注,可以针对某域名清除,否则是全清  
  7. //                             {  
  8.                                  [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes  
  9.                                                                            forDataRecords:@[record]  
  10.                                                                         completionHandler:^{  
  11.                                                                             NSLog(@"Cookies for %@ deleted successfully",record.displayName);  
  12.                                                                         }];  
  13. //                             }  
  14.                          }  
  15.                      }];  

但显然大多小伙伴们都需要支持IOS8的,所以尴尬的是上面的方法暂时用不到,所以还是老老实实的这么干XD

--------------IOS8以上---------------

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  2. NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];  
  3. NSError *errors;  
  4. [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors]; 


//弹窗处理

转自:http://qiita.com/ShingoFukuyama/items/5d97e6c62e3813d1ae98

wkwebview_uidelegate.png

左から、JavaScriptのalert,confirm,promptが実行された時の画面です。

以下WKUIDelegateのみを使うことを目的としたコードを記します。

iOS8であればXcodeで新規作成時にSingle View Applicationテンプレートを作成し、ViewController.mにコピペするだけで動きますのでお試しください。

//
//  ViewController.m
//  MyWKWebView
//
//  Created by FukuyamaShingo on 9/22/14.
//  Copyright (c) 2014 Shingo Fukuyama. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()
<WKUIDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UIBarButtonItem *buttonForAlert;
@property (nonatomic, strong) UIBarButtonItem *buttonForConfirm;
@property (nonatomic, strong) UIBarButtonItem *buttonForPrompt;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    /*
     * Setup WKWebView only for WKUIDelegate
     */
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    _webView.UIDelegate = self;
    NSString *urlString = @"https://www.google.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];


    /*
     * Setup Toolbar
     */
    _buttonForAlert = [[UIBarButtonItem alloc] initWithTitle:@"Alert"
                                                       style:UIBarButtonItemStylePlain
                                                      target:self
                                                      action:@selector(showAlert:)];
    _buttonForConfirm = [[UIBarButtonItem alloc] initWithTitle:@"Confirm"
                                                         style:UIBarButtonItemStylePlain
                                                        target:self
                                                        action:@selector(showConfirm:)];
    _buttonForPrompt = [[UIBarButtonItem alloc] initWithTitle:@"Prompt"
                                                        style:UIBarButtonItemStylePlain
                                                       target:self
                                                       action:@selector(showPrompt:)];
    _buttonForAlert.width   = 80.0;
    _buttonForConfirm.width = 80.0;
    _buttonForPrompt.width  = 80.0;
    _toolbar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                            target:nil
                                                                            action:nil];
    _toolbar.items = @[_buttonForAlert, spacer, _buttonForConfirm, spacer, _buttonForPrompt];

    [self.view addSubview:_webView];
    [self.view addSubview:_toolbar];
    [self setupConstraints];
}

- (void)showAlert:(UIBarButtonItem *)sender
{
    NSString *promptCode = @"alert('Alertが押されました');";
    [_webView evaluateJavaScript:promptCode completionHandler:^(id object, NSError *error) { }];
}

- (void)showConfirm:(UIBarButtonItem *)sender
{
    NSString *promptCode = @"var confirmed = confirm('OK?');";
    [_webView evaluateJavaScript:promptCode completionHandler:^(id object, NSError *error) { }];
}

- (void)showPrompt:(UIBarButtonItem *)sender
{
    NSString *promptCode = @"var person = prompt('名前を入力してください', 'デフォルト');";
    [_webView evaluateJavaScript:promptCode completionHandler:^(id object, NSError *error) { }];
}


#pragma mark - WKUIDelegate

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler
{
    NSString *hostString = webView.URL.host;
    NSString *sender = [NSString stringWithFormat:@"%@からの表示", hostString];

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:sender preferredStyle:UIAlertControllerStyleAlert];

    [alertController addAction:[UIAlertAction actionWithTitle:@"閉じる" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler
{
    NSString *hostString = webView.URL.host;
    NSString *sender = [NSString stringWithFormat:@"%@からの表示", hostString];

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:sender preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        //textField.placeholder = defaultText;
        textField.text = defaultText;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *input = ((UITextField *)alertController.textFields.firstObject).text;
        completionHandler(input);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler(nil);
    }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
    NSString *hostString = webView.URL.host;
    NSString *sender = [NSString stringWithFormat:@"%@からの表示", hostString];

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:sender preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler(YES);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alertController animated:YES completion:^{}];
}


#pragma mark - Constraints

- (void)setupConstraints
{
    _webView.translatesAutoresizingMaskIntoConstraints = NO;
    [_webView.superview addConstraints:[NSLayoutConstraint
                                        constraintsWithVisualFormat:@"V:|-20.0-[view]-44.0-|"
                                        options:NSLayoutFormatDirectionLeadingToTrailing
                                        metrics:nil
                                        views:@{@"view":_webView}]];
    [_webView.superview addConstraints:[NSLayoutConstraint
                                        constraintsWithVisualFormat:@"H:|-0-[view]-0-|"
                                        options:NSLayoutFormatDirectionLeadingToTrailing
                                        metrics:nil
                                        views:@{@"view":_webView}]];

    _toolbar.translatesAutoresizingMaskIntoConstraints = NO;
    [_toolbar.superview addConstraints:[NSLayoutConstraint
                                        constraintsWithVisualFormat:@"V:[view]-0-|"
                                        options:NSLayoutFormatDirectionLeadingToTrailing
                                        metrics:nil
                                        views:@{@"view":_toolbar}]];
    [_toolbar.superview addConstraints:[NSLayoutConstraint
                                        constraintsWithVisualFormat:@"H:|-0-[view]-0-|"
                                        options:NSLayoutFormatDirectionLeadingToTrailing
                                        metrics:nil
                                        views:@{@"view":_toolbar}]];
    [_toolbar.superview addConstraint:[NSLayoutConstraint constraintWithItem:_toolbar
                                                               attribute:NSLayoutAttributeHeight
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:nil
                                                               attribute:0
                                                              multiplier:1.0
                                                                constant:44.0]];

}

@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值