Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)     } } 
like image 248
sebbo Avatar asked Oct 06 '14 15:10

sebbo


People also ask

How do I find user agent in Swift?

Swift. let userAgent = UAString() if let url = NSURL(string: "") { let request = NSMutableURLRequest(url: url as URL) request. setValue(userAgent, forHTTPHeaderField: "User-Agent") //... }

Is User Agent a header?

The user agent is an HTTP header that web browsers and other web applications use to identify themselves and their capabilities.

What is the use of user agent request header?

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.


1 Answers

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"]) 
like image 131
sebbo Avatar answered Sep 22 '22 13:09

sebbo