You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift中如何为所有链接(含重定向)设置User Agent?

解决WKWebView自定义User Agent不生效(含重定向请求)的问题

你的代码核心问题在于:重定向请求不会自动沿用customUserAgent设置,且你在decidePolicyFor代理方法中仅重新赋值了customUserAgent,但没有修改当前导航请求的UA头,导致默认UA依然生效。

修正方案

  1. 初始化WebView时就设置customUserAgent,确保首次加载请求使用自定义UA
  2. 在导航代理方法中,手动检查并修改每个请求(包括重定向)的UA头,确保所有请求统一使用自定义值

修正后的完整代码

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    
    var webView: WKWebView!
    let customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3.1 Safari/605.1.15"
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        // 初始化阶段就配置自定义UA
        webView.customUserAgent = customUserAgent
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        guard let targetURL = URL(string: "https://test.com/") else { return }
        let request = URLRequest(url: targetURL)
        webView.load(request)
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let currentRequestUA = navigationAction.request.value(forHTTPHeaderField: "User-Agent")
        
        // 检查当前请求UA是否匹配自定义值,不匹配则修改
        if currentRequestUA != customUserAgent {
            var mutableRequest = navigationAction.request
            mutableRequest.setValue(customUserAgent, forHTTPHeaderField: "User-Agent")
            
            // 取消原请求,加载修改UA后的新请求
            decisionHandler(.cancel)
            webView.load(mutableRequest)
        } else {
            decisionHandler(.allow)
        }
    }
}

关键修改说明

  • 将customUserAgent的配置提前到WebView初始化后,确保WebView的基础UA设置正确
  • 在decidePolicyFor中,通过创建可变请求副本手动设置UA头,处理重定向及后续所有请求的UA一致性
  • 替换强制解包为可选绑定,提升代码稳定性

内容的提问来源于stack exchange,提问作者Vector

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 16:33:31