How can I set the "User-Agent" header of a UIWebView in Swift

sebbo picture sebbo · Oct 6, 2014 · Viewed 30.3k times · Source

I am using Xcode 6 for an iOS App with Swift. I have got a simple ViewController with an embedded UIWebView. You can find the code below. Now I want to change the User-Agent HTTP header. I tried to use the setValue method of NSURLRequest but it didn't work (see uncommented line). Does anyone know how to do that?

import UIKit

class WebViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidAppear(animated: Bool) {
        var url = NSURL(string: "https://www.samplepage.com")

        var request = NSMutableURLRequest(URL: url)

        // request.setValue("Custom-Agent", forHTTPHeaderField: "User-Agent")

        webView.loadRequest(request)
    }
}

Answer

sebbo picture sebbo · Oct 6, 2014

This will change the agent of any call made through the 'normal' stack.

Swift 2:

NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Custom-Agent"])

Swift 3:

UserDefaults.standard.register(defaults: ["UserAgent": "custom value"])