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) } }
Swift. let userAgent = UAString() if let url = NSURL(string: "") { let request = NSMutableURLRequest(url: url as URL) request. setValue(userAgent, forHTTPHeaderField: "User-Agent") //... }
The user agent is an HTTP header that web browsers and other web applications use to identify themselves and their capabilities.
The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.
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"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With