Gleb Kalachev
Gleb Kalachev

Reputation: 133

How to request desktop site in Swift programmatically (without UIWebView)?

Desktop site's HTML code has a link of "apple-touch-icon" thumbnail image in header, whereas mobile's one hasn't. I just need to fetch this html and parse.

So, how to request desktop site (maybe via URLRequest, URLSession or something else)?

p.s. I found, that I have to change User-Agent string value, but again, I didn't find, how to do this in Swift.

Upvotes: 0

Views: 2472

Answers (2)

MichaelV
MichaelV

Reputation: 1261

Depends on server logic, but in most cases it's enough to set up userAgent Header in you request:

let url = URL(string:"https://google.com")!
var request = URLRequest(url: url)
let userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/605.1.12 (KHTML, like Gecko) Version/11.1 Safari/605.1.12"
request.addValue(userAgent, forHTTPHeaderField: "User-Agent")

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
 // Process reponse
}
task.resume()

Upvotes: 3

Yaco Zaragoza
Yaco Zaragoza

Reputation: 437

A WKWebView should solve your problem - you can define it in your code. Do this:

var webView : WKWebView!
override func loadView() {
    super.loadView()

    let config = WKWebViewConfiguration()
    webView = WKWebView(frame: self.view.frame, configuration: config)
    self.webView!.uiDelegate = self
    webView.customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36"
    //load URL here
    let url = NSURL(string: "https://stackoverflow.com/")!
    webView.load(URLRequest(url: url as URL))
    self.view.addSubview(webView)


}

Upvotes: 2

Related Questions