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

Swift 4中如何为WKWebView指定设备User Agent?

How to Force WKWebView to Load Mobile Site in Swift 4

Hey there! The issue you're facing is super common—WKWebView defaults to a desktop-style user agent, which is why sites are serving you the desktop version. Let's fix that by setting a mobile-specific user agent. Here are a couple of reliable ways to do it:

Option 1: Set a Global Mobile User Agent (All Requests)

This method sets the user agent for every request your WKWebView makes, so all pages will load the mobile version. Perfect if you want consistent behavior across the entire web view.

Modify your viewDidLoad method like this:

import UIKit
import WebKit

class ViewController: UIViewController {
    var website = "https://www.example.com"
    @IBOutlet var webpage: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set a mobile user agent (update this to match your target iOS version if needed)
        let mobileUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
        webpage.customUserAgent = mobileUserAgent
        
        // Load your request safely
        guard let url = URL(string: website) else { return }
        let request = URLRequest(url: url)
        webpage.load(request)
    }
}

Option 2: Dynamically Modify the Default User Agent

Instead of hardcoding a user agent, you can tweak the default one WKWebView uses. This is more future-proof because it adapts to the device's actual iOS version:

import UIKit
import WebKit

class ViewController: UIViewController {
    var website = "https://www.example.com"
    @IBOutlet var webpage: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Get the default user agent first (async call)
        webpage.evaluateJavaScript("navigator.userAgent") { [weak self] result, error in
            guard let self = self, let defaultAgent = result as? String else {
                // Fallback to hardcoded agent if evaluation fails
                let fallbackAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
                self.webpage.customUserAgent = fallbackAgent
                self.loadWebsite()
                return
            }
            
            // Swap desktop identifier with mobile to mimic an iPhone
            let mobileAgent = defaultAgent.replacingOccurrences(of: "Macintosh", with: "iPhone")
            self.webpage.customUserAgent = mobileAgent
            self.loadWebsite()
        }
    }
    
    private func loadWebsite() {
        guard let url = URL(string: website) else { return }
        let request = URLRequest(url: url)
        webpage.load(request)
    }
}

This approach uses evaluateJavaScript to fetch the default agent, adjusts it to look like an iPhone, then loads your site once the agent is set. The helper method keeps the code clean since we have to wait for the async evaluation to finish.

Option 3: Set User Agent for Individual Requests

If you only want specific requests to use the mobile agent, add the User-Agent header directly to your URLRequest:

override func viewDidLoad() {
    super.viewDidLoad()
    
    guard let url = URL(string: website) else { return }
    var request = URLRequest(url: url)
    
    // Add mobile user agent header to this specific request
    let mobileUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
    request.setValue(mobileUserAgent, forHTTPHeaderField: "User-Agent")
    
    webpage.load(request)
}

Note: This only applies to the initial request. If users navigate to other pages in the web view, those requests won't carry the header unless you implement WKNavigationDelegate's decidePolicyFor method to modify each subsequent request's headers.

Whichever option you pick, test it with your target website—some sites have unique user agent logic, but these methods should get you the mobile view almost every time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:47:14