# 1. iOS12 设置 WKWebView 的 UserAgent

**作者**: [高老师很忙](https://weibo.com/517082456)

最近发现，在 `iOS12` 上通过图1的方式去设置 `WKWebView` 的 `UserAgent` 会失效，

![图1](/files/-LUYjimV2XpRqPzt1bxJ)

在 `iOS12以下` 这段代码是我们预期的结果（如图2），

![图2](/files/-LUYjimXLAEfOzZPVBeB)

在 `iOS12` (16A366)上却发现出现了问题（图3）。

![图3](/files/-LUYjimZoh9UYrTGlLJE)

偶然发现如果在设置 `customUserAgent` 之前没有调用过 `webView.evaluateJavaScript(“navigator.userAgent”)` ，设置 `customUserAgent` 是可以设置成功的（图4），

![图4](/files/-LUYjima-AEUHOVTaawo)

如果在之前调用过（图1，图5），就会悲剧。

![图1](/files/-LUYjimcHh3AllDSifJE)

![图5](/files/-LUYjimeLTsdaxZkvLJ6)

如果因为一些特殊原因，需要在调用 `webView.evaluateJavaScript(“navigator.userAgent”)` 之后设置 `customUserAgent` 的情况，在 `didFinishNavigation` 回调里执行一次 `reload`，在下一次 `didFinishNavigation` 回调之后已经正确设置 `UserAgent`（图6），注意不要循环调用哦！

![图6](/files/-LUYjimgx4HzBse73VPu)

或者粗暴点，直接延迟几秒调用 `reload`（图7）。

![图7](/files/-LUYjimiXqnigpnelfld)

因为最近非常非常忙，所以还没有去深度研究，之后会找时间会深度研究一下，如果有研究过，欢迎一起讨论分享。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://awesome-tips.gitbook.io/ios/webview/content.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
