iOS 12.0系統(tǒng)設(shè)置UserAgent不生效解決

因?yàn)槲覀僡pp原生和H5交互都是依靠設(shè)置WKWebView的userAgent實(shí)現(xiàn)交互,線上反饋一臺(tái)手機(jī)點(diǎn)擊按鈕沒反應(yīng),因?yàn)辄c(diǎn)擊按鈕是給到原生端處理,通過日志發(fā)現(xiàn)設(shè)置userAgent不成功導(dǎo)致。

解決方法如下:

網(wǎng)上資料如下,都是創(chuàng)建一個(gè)假的webView,最后設(shè)置真是webView的userAgent即可。

這么做確實(shí)是首個(gè)頁面設(shè)置成功了,但是進(jìn)到app里面頁面又存在設(shè)置不上的問題,因?yàn)槲覀兊脑O(shè)置userAgent的都是在每個(gè)webView的didStartProvisionalNavigation代理方法設(shè)置的。

最后是在AppDelegate文件全局設(shè)置userAgent解決了。

代碼如下:

#pragma mark - 設(shè)置全局userAgent
//修改userAgent
- (void)addToWebViewUserAgent {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        WKWebView *webView = [WKWebView new];
        [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable oldAgent, NSError * _Nullable error) {
            if (![oldAgent isKindOfClass:[NSString class]]) {
                // 為了避免沒有獲取到oldAgent,所以設(shè)置一個(gè)默認(rèn)的userAgent
                // Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
                oldAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU iPhone OS %@ like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148", [[UIDevice currentDevice] model], [[[UIDevice currentDevice] systemVersion] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
            }
            
            NSString *userAgent = oldAgent;
            //修改UserAgent
            NSString *newUserAgent = [userAgent stringByAppendingString:@"C2Mobile/{1.0.0}"];
            if (![newUserAgent containsString: @" SmartChasing"]) {
                //修改UserAgent
               newUserAgent = [newUserAgent stringByAppendingString:@" SmartChasing"];
            }
            NSString *barHeight = [NSString stringWithFormat:@";statusBarHeight:%f",kStatusBarHeight];
            newUserAgent = [newUserAgent stringByAppendingString:barHeight];
            [webView setCustomUserAgent:newUserAgent];
            NSDictionary *userAgentDic = @{@"UserAgent": newUserAgent};
            [[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDic];
        }];
    });
}

參考鏈接:

https://blog.csdn.net/qq_26697709/article/details/105961034

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容