flutter 插件webview_flutter一系列問題總結(jié)

項(xiàng)目最初使用的是flutter_webview_plugin這個插件,會出現(xiàn)paypal登錄界面一直加載不出來的情況蟆融,后來使用了官方插件webview_flutter草巡,就解決了這個問題,然后就改用成了這個插件型酥。后面隨著需求的增加山憨,也遇到了一系列的問題(iOS上)。

修改webview_flutter代碼的方法:

修改webview_flutter插件中的代碼弥喉,如果只是修改了本地插件的代碼郁竟,這樣會有一些弊端:

  • 插件升級之后,之前修改的代碼被覆蓋掉了由境。
  • 一起合作的小伙伴同步代碼很不方便棚亩。
所以會使用自己的插件地址來管理(這樣也會有不好的地方是沒有辦法使自己的插件更新到官方插件的最新版本,fork的時候是什么版本,以后也會是什么版本)蔑舞。

步驟:

  • 找到webview_flutter插件的GitHub地址
  • fork一份到自己的GitHub上生成一個新的地址
  • 要修改這個插件的人clone到本地拒担,如果沒有權(quán)限需要獲取權(quán)限
  • 打開插件里面的example項(xiàng)目,可以對插件進(jìn)行改造以及測試了
  • 使用的時候攻询,webview_flutter: git: git地址从撼,不再是之前的webview_flutter: 版本號
問題1、webView內(nèi)facebook登錄界面不能跳轉(zhuǎn)钧栖,只是刷新了當(dāng)前界面低零。在瀏覽器上可以看見facebook登錄是彈出了一個彈框,相當(dāng)于又打開了一個新窗口拯杠,所以在app內(nèi)WKWebview沒有處理這種情況掏婶。
解決:

在FlutterWebView.m文件中實(shí)現(xiàn)WKWebview的UIDelegate的一個代理方法

//初始化方法里面添加
_webView.UIDelegate = self;

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame && [navigationAction.request.URL.absoluteString hasPrefix:@"https://m.facebook"]) {
        WKWebView *popup = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
        popup.UIDelegate = self;
        popup.navigationDelegate = _navigationDelegate;
        [self.view addSubview:popup];
      
        return popup;
    }else if (navigationAction.targetFrame == nil){
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

意思是當(dāng)判斷是facebook登錄的時候,又創(chuàng)建了一個新的WKWebview覆蓋在上面潭陪,解決了問題雄妥。

問題2:添加進(jìn)度條:
-(void)showProgress{
    [self->_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self->_webView.frame), 3)];
    progress.backgroundColor = [UIColor clearColor];
    [self->_webView addSubview:progress];
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 3);
    layer.backgroundColor = [[UIColor orangeColor] CGColor];
    [progress.layer addSublayer:layer];
    self->_progresslayer = layer;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        _progresslayer.opacity = 1;
        _progresslayer.frame = CGRectMake(0, 0, _webView.bounds.size.width * [change[@"new"] floatValue], 3);
        
        if ([change[@"new"] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self->_progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self->_progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

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

問題3:添加類似于手機(jī)上Safari瀏覽器上的底部可以前進(jìn)后退的工具條,并且當(dāng)不可前進(jìn)后退的時候依溯,按鈕顯示灰色老厌。遇到的問題是由于上面facebook登錄時候的特殊處理,是在webview上又疊加了一個webview黎炉,前進(jìn)后退就需要特殊處理枝秤。

添加底部工具條的代碼,以及點(diǎn)擊方法:

-(void)showToolbar{
    UIWindow * window = [[UIApplication sharedApplication] windows].firstObject;
    UIToolbar * toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, _webView.frame.size.height, window.bounds.size.width, TOOBAR_HEIGHT)];
    toolbar.translucent = NO;
    [toolbar setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
    UIBarButtonItem * leftSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    [leftSpaceItem setWidth:40.0];
    // back button
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"Slice-left-gray"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(goBackClick)];
    backButton.enabled = NO;
    self.backButtonItem = backButton;
    
    UIBarButtonItem * rightSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    [rightSpaceItem setWidth:90.0];
    
    
    // forward button
    UIBarButtonItem *forwardButton = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"Slice-right-gray"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(goForwardClick)];
    forwardButton.enabled = NO;
    self.forwardButtonItem = forwardButton;
    
    toolbar.items = @[leftSpaceItem,backButton,rightSpaceItem,forwardButton];
    [self.view addSubview:toolbar];
    _webView.toolBar = toolbar;
    self.toolbar = toolbar;
}


-(void)goBackClick{
    if([self.currentWebview canGoBack]){
        WKNavigation * navigation = [self.currentWebview goBack];
        if(navigation == nil){
            [self.currentWebview reload];
        }
    }else{
        if(self.currentWebview != _webView){
            [self.currentWebview removeFromSuperview];
            self.currentIndex--;
            if(self.currentIndex >= 0){
                self.currentWebview = self.webviewArr[self.currentIndex];
            }
            if(self.forwardButtonItem.enabled == NO){
                self.forwardButtonItem.enabled = YES;
                self.forwardButtonItem.image = [[UIImage imageNamed:@"Slice-right"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }
            self.backButtonItem.enabled = [self.currentWebview canGoBack];
            self.backButtonItem.image = [self.currentWebview canGoBack] ? [[UIImage imageNamed:@"Slice-left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] : [[UIImage imageNamed:@"Slice-left-gray"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
        
    }
}

-(void)goForwardClick{
    if([self.currentWebview canGoForward]){
        WKNavigation * navigation = [self.currentWebview goForward];
        if(navigation == nil){
            [self.currentWebview reload];
        }
    }else{
        if(self.currentIndex+1 < self.webviewArr.count){
            self.currentIndex++;
            [self.view addSubview:self.webviewArr[self.currentIndex]];
            [self.view bringSubviewToFront:self.toolbar];
            self.currentWebview = self.webviewArr[self.currentIndex];
            if(self.backButtonItem.enabled == NO){
                self.backButtonItem.enabled = YES;
                self.backButtonItem.image = [[UIImage imageNamed:@"Slice-left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }
            self.forwardButtonItem.enabled = [self.currentWebview canGoForward];
            self.forwardButtonItem.image = [self.currentWebview canGoForward] ? [[UIImage imageNamed:@"Slice-right"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] : [[UIImage imageNamed:@"Slice-right-gray"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
}

解決的思路是慷嗜,將所有的webView添加到一個數(shù)組中淀弹,記錄下來,并且把當(dāng)前的webView的index也記錄下來庆械,根據(jù)當(dāng)前的index和webView的數(shù)量之間的關(guān)系薇溃,判斷是否可以前進(jìn),重新添加或移除上面覆蓋的webView干奢。

還要做一些特殊的處理痊焊,當(dāng)點(diǎn)擊webvVew上的某個地方,比如打開facebook忿峻,就會創(chuàng)建一個新的webView覆蓋在上面薄啥,點(diǎn)擊回退,移除這個webView逛尚,再點(diǎn)擊界面上的一個鏈接跳轉(zhuǎn)一個界面(還是在該webView內(nèi))垄惧,這個時候是不是就需要將那個新建的webView,從數(shù)組中移除掉了。

在createWebViewWithConfiguration代理方法中添加代碼:

     [self.view bringSubviewToFront:self.toolbar];
     if (self.currentIndex+1 < self.webviewArr.count) {
         [self.webviewArr removeObjectsInRange:NSMakeRange(self.currentIndex+1, self.webviewArr.count-1-self.currentIndex)];
     }
       
     self.currentWebview = popup;
     self.currentIndex++;
     if (self.backButtonItem.enabled == NO) {
         self.backButtonItem.enabled = YES;
         self.backButtonItem.image = [[UIImage imageNamed:@"Slice-left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
     }

還有一個地方需要移除绰寞,監(jiān)聽webView請求的代理方法到逊,由于插件里面navigationDelegate指向的是FLTWKNavigationDelegate類铣口,需要拿到這個里面decidePolicyForNavigationAction代理方法的回調(diào)。

_navigationDelegate = [[FLTWKNavigationDelegate alloc] initWithChannel:_channel];
      _navigationDelegate.delegate = self;
    _webView.navigationDelegate = _navigationDelegate;

所以會在FLTWKNavigationDelegate中寫一個代理方法觉壶,通知FLTWebViewController這個類脑题,每次請求都會觸發(fā)這個方法⊥校回調(diào)方法代碼:

-(void)requstWithAction:(WKNavigationAction*)action{
    if(action.targetFrame && !action.targetFrame.isMainFrame && action.sourceFrame.isMainFrame && action.navigationType != WKNavigationTypeBackForward){
        if (self.currentIndex+1 < self.webviewArr.count) {
            [self.webviewArr removeObjectsInRange:NSMakeRange(self.currentIndex+1, self.webviewArr.count-1-self.currentIndex)];
        }
    }
}
監(jiān)聽webView是否可以前進(jìn)和后退叔遂,最開始的思路是在點(diǎn)擊前進(jìn)后退按鈕的點(diǎn)擊方法中實(shí)現(xiàn),但是這樣處理是不準(zhǔn)確的争剿,所以使用kvo方法實(shí)現(xiàn):
//初始化方法中添加
[self->_webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
[self->_webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];

//監(jiān)聽回調(diào)方法中添加
if([keyPath isEqualToString:@"canGoBack"]){
    BOOL isCanGoBack = [change[@"new"] boolValue];
    if (self.currentWebview != _webView) {
        isCanGoBack = YES;
    }
    self.backButtonItem.enabled = isCanGoBack;
    self.backButtonItem.image = isCanGoBack ? [[UIImage imageNamed:@"Slice-left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] : [[UIImage imageNamed:@"Slice-left-gray"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}else if([keyPath isEqualToString:@"canGoForward"]){
    BOOL isCanForward = [change[@"new"] boolValue];
    if (self.currentIndex < self.webviewArr.count-1) {
        isCanForward = YES;
    }
    self.forwardButtonItem.enabled = isCanForward;
    self.forwardButtonItem.image = isCanForward ? [[UIImage imageNamed:@"Slice-right"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] : [[UIImage imageNamed:@"Slice-right-gray"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

一些特殊的處理上面的代碼中已經(jīng)涵蓋了

問題4:工具欄擋住了webView底部的內(nèi)容

需要將webView的高度減少一個工具欄的高度已艰,工具欄頂端為webView的最底端。
但是發(fā)現(xiàn)沒有設(shè)置webView的frame的地方蚕苇,初始化方法傳進(jìn)來的frame也是0,0,0,0哩掺,webView的大小是根據(jù)flutter的代碼來確定的,又不能改flutter代碼涩笤,不是在控制器里面嚼吞,不能明確知道webView初始化完成的具體時間,所以只能監(jiān)聽webView的frame的改變了辆它,但是在監(jiān)聽回調(diào)方法中再設(shè)置frame的話偿衰,會造成死循環(huán)软舌,所以做了以下處理:

//初始化方法里面添加
[self->_webView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];

if([keyPath isEqualToString:@"frame"]){
        CGRect rect = [change[@"new"] CGRectValue];
        if (rect.size.height > 0 && self.isFirstInvoke == YES) {
            self.isFirstInvoke = NO;
            CGRect newRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-TOOBAR_HEIGHT);
            _webView.frame = newRect;
        }
    }

這樣處理完之后發(fā)現(xiàn)會出現(xiàn)一個問題,工具欄上的前進(jìn)后退按鈕不響應(yīng)了恕曲,是因?yàn)槌隽烁缚丶狞c(diǎn)擊區(qū)域切心,所以創(chuàng)建了WKWebview子類飒筑,在子類中處理點(diǎn)擊區(qū)域:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {

    if (!CGRectContainsPoint(self.bounds, point)) {
        CGPoint newPoint = [self convertPoint:point toView:self.toolBar];
        if (CGRectContainsPoint(self.toolBar.bounds, newPoint)) {
            return YES;
        }
        return NO;
    }
    return YES;
}

至此,這就是我開發(fā)中遇到的幾個問題了绽昏,希望對你們有所幫助哦协屡。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市全谤,隨后出現(xiàn)的幾起案子肤晓,更是在濱河造成了極大的恐慌,老刑警劉巖认然,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件补憾,死亡現(xiàn)場離奇詭異,居然都是意外死亡卷员,警方通過查閱死者的電腦和手機(jī)盈匾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來毕骡,“玉大人削饵,你說我怎么就攤上這事岩瘦。” “怎么了窿撬?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵启昧,是天一觀的道長。 經(jīng)常有香客問我劈伴,道長密末,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任宰啦,我火速辦了婚禮苏遥,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘赡模。我一直安慰自己田炭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布漓柑。 她就那樣靜靜地躺著教硫,像睡著了一般。 火紅的嫁衣襯著肌膚如雪辆布。 梳的紋絲不亂的頭發(fā)上瞬矩,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天,我揣著相機(jī)與錄音锋玲,去河邊找鬼景用。 笑死,一個胖子當(dāng)著我的面吹牛惭蹂,可吹牛的內(nèi)容都是我干的伞插。 我是一名探鬼主播,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼盾碗,長吁一口氣:“原來是場噩夢啊……” “哼媚污!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起廷雅,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤耗美,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后航缀,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體商架,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年谬盐,在試婚紗的時候發(fā)現(xiàn)自己被綠了甸私。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡飞傀,死狀恐怖皇型,靈堂內(nèi)的尸體忽然破棺而出诬烹,到底是詐尸還是另有隱情,我是刑警寧澤弃鸦,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布绞吁,位于F島的核電站,受9級特大地震影響唬格,放射性物質(zhì)發(fā)生泄漏家破。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一购岗、第九天 我趴在偏房一處隱蔽的房頂上張望汰聋。 院中可真熱鬧,春花似錦喊积、人聲如沸烹困。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽髓梅。三九已至,卻和暖如春绎签,著一層夾襖步出監(jiān)牢的瞬間枯饿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工奢方, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人爸舒。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓袱巨,卻偏偏與公主長得像,于是被迫代替她去往敵國和親碳抄。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評論 2 359

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