WKWebView踩坑飄過

替換WKWebView的原因有:

內(nèi)存占用少

項目h5較多墓怀,發(fā)現(xiàn)當(dāng)有高清圖或gif時在4s上crash較多,幾乎都是內(nèi)存原因卫键。WKWebView占用內(nèi)存較少傀履,立馬簡單的測試下,原本必掛的網(wǎng)頁運行正常莉炉,決定換钓账。

#import <WebKit/WebKit.h>
- (void)viewDidLoad {
    [super viewDidLoad];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    [self.view addSubview:_webView];
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]];
    [_webView loadRequest:request];
    ...
}

進度容易獲取碴犬,無需引用第三方框架

首先看下,WKWebView的estimatedProgress屬性注解

/*! @abstract An estimate of what fraction of the current navigation has been completed.
 @discussion This value ranges from 0.0 to 1.0 based on the total number of
 bytes expected to be received, including the main document and all of its
 potential subresources. After a navigation completes, the value remains at 1.0
 until a new navigation starts, at which point it is reset to 0.0.
 @link WKWebView @/link is key-value observing (KVO) compliant for this
 property.
 */

注冊通知:

- (void)viewDidLoad
    [super viewDidLoad];
    ...
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

響應(yīng)官扣,progressView用的是開源的NJKWebViewProgressView:


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        GTRWeakSelf
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.webViewProgressView setProgress:newprogress animated:YES];
        });
        
    }
}

移除:

- (void)dealloc {
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

js與native通訊方式多樣化翅敌,和android統(tǒng)一,但不支持javascript core

1惕蹄、js使用alert蚯涮、prompt和confirm等方式,wkwebview用

native:
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

2卖陵、URL方式遭顶,如果地址是網(wǎng)絡(luò)上,可把html放到本地可解決

js:
<script language="javascript">
            function loadURL(url) {
                var iFrame;
                iFrame = document.createElement("iframe");
                iFrame.setAttribute("src", url);
                iFrame.setAttribute("style", "display:none;");
                iFrame.setAttribute("height", "0px");
                iFrame.setAttribute("width", "0px");
                iFrame.setAttribute("frameborder", "0");
                document.body.appendChild(iFrame);
                // 發(fā)起請求后這個iFrame就沒用了泪蔫,所以把它從dom上移除掉
                iFrame.parentNode.removeChild(iFrame);
                iFrame = null;
            }
            function getVersion() {
                loadURL("gtrAction://getVersion");
            }
</script>

native:
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"haleyaction"]) {
        
        [self handleCustomAction:URL];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

3棒旗、用MessageHandler方式,我們選擇這種方式實現(xiàn)撩荣。

js實現(xiàn):
 window.webkit.messageHandlers.<name>.postMessage(<messageBody>)
native實現(xiàn)祥見集成問題實現(xiàn)铣揉。

集成問題

WKWebView使用有循環(huán)引用,原因是UIViewController->WKWebView->WKWebViewConfiguration->WKUserContentController餐曹,最后WKUserContentController在addScriptMessageHandler:name:又引用UIViewController逛拱。

有2個解決方案:

1、這種方式簡單台猴,只需在viewWillAppear和viewWillDisappear相應(yīng)的添加和刪除messageHandler朽合。不過部分系統(tǒng)上再次addScriptMessageHandler無效。

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getVersion"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"getVersion"];
}
- (void)dealloc {
    DebugLog(@"GTRViewController dealloc");
}

2饱狂、打破addScriptMessageHandler這個循環(huán)引用曹步,用中間代理方式實現(xiàn)。

GTRWeakScriptMessageDelegate.h

#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>

@protocol GTRWeakScriptMessageDelegate <NSObject>
- (void)getVersion;
@end

@interface GTRWeakScriptMessageDelegate : NSObject <WKScriptMessageHandler>
@property (nonatomic, weak) id <GTRWeakScriptMessageDelegate> gDelegate;

- (instancetype)initWithDelegate:(id <GTRWeakScriptMessageDelegate>)delegate;
@end

GTRWeakScriptMessageDelegate.m

#import "GTRWeakScriptMessageDelegate.h"

@interface GTRWeakScriptMessageDelegate () 

@end

@implementation GTRWeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id <GTRWeakScriptMessageDelegate>)delegate {
    self = [super init];
    if (self) {
        self.gDelegate = delegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if (![self.gDelegate conformsToProtocol:@protocol(GTRWeakScriptMessageDelegate)]) {
        return;
    }
    
    if ([message.name isEqualToString:@"getVersion"]) {
        //異步回掉
        [self.gDelegate getVersion];
    }
}

- (void)dealloc {
    DebugLog(@"GTRWeakScriptMessageDelegate dealloc");
}

@end

GTRViewController.m

@property (nonatomic, strong) GTRWeakScriptMessageDelegate *weakScriptDelegate;
- (void)viewDidLoad {
    [super viewDidload];
    _weakScriptDelegate = [[GTRWeakScriptMessageDelegate alloc] initWithDelegate:self];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    //添加messageHandler
    [_webView.configuration.userContentController addScriptMessageHandler:self.weakScriptDelegate name:@"getVersion"];
    
    _webView.scrollView.delegate = self;
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    [self.view addSubview:_webView];
}

- (void)dealloc {
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"getVersion"];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    _webView.UIDelegate = nil;
    _webView.navigationDelegate = nil;
    _webView.scrollView.delegate = nil;
    DebugLog(@"GTRViewController dealloc");
}

附送wkwebview修改Agent休讳,用來標(biāo)示是應(yīng)用內(nèi)web讲婚,ios9后用setCustomUserAgent:方法.

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" ua gtr_demo"];//自定義需要拼接的字符串
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

GTRViewController.m
- (void)viewDidLoad {
    ...
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        DebugLog(@"Webview UserAgent:%@", result);
    }];
    ...
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市俊柔,隨后出現(xiàn)的幾起案子磺樱,更是在濱河造成了極大的恐慌,老刑警劉巖婆咸,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竹捉,死亡現(xiàn)場離奇詭異,居然都是意外死亡尚骄,警方通過查閱死者的電腦和手機块差,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人憨闰,你說我怎么就攤上這事状蜗。” “怎么了鹉动?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵轧坎,是天一觀的道長。 經(jīng)常有香客問我泽示,道長缸血,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任械筛,我火速辦了婚禮捎泻,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘埋哟。我一直安慰自己笆豁,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布赤赊。 她就那樣靜靜地躺著闯狱,像睡著了一般。 火紅的嫁衣襯著肌膚如雪抛计。 梳的紋絲不亂的頭發(fā)上哄孤,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天,我揣著相機與錄音爷辱,去河邊找鬼。 笑死朦肘,一個胖子當(dāng)著我的面吹牛饭弓,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播媒抠,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼弟断,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了趴生?” 一聲冷哼從身側(cè)響起阀趴,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎苍匆,沒想到半個月后刘急,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡浸踩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年叔汁,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡据块,死狀恐怖码邻,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情另假,我是刑警寧澤像屋,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站边篮,受9級特大地震影響己莺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜苟耻,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一篇恒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧凶杖,春花似錦胁艰、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至射富,卻和暖如春费变,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背漆撞。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工殴泰, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人浮驳。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓悍汛,卻偏偏與公主長得像,于是被迫代替她去往敵國和親至会。 傳聞我的和親對象是個殘疾皇子离咐,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容