如何以编程方式在 Swift 中请求桌面站点(没有 UIWebView)? [英] How to request desktop site in Swift programmatically (without UIWebView)?

查看:28
本文介绍了如何以编程方式在 Swift 中请求桌面站点(没有 UIWebView)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

桌面站点的 HTML 代码在标题中有一个apple-touch-icon"缩略图链接,而移动站点没有.我只需要获取这个 html 并解析.

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.

那么,如何请求桌面站点(可能通过 URLRequest、URLSession 或其他方式)?

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

附言我发现,我必须更改 User-Agent 字符串值,但同样,我没有找到,如何在 Swift 中执行此操作.

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.

推荐答案

取决于服务器逻辑,但在大多数情况下,在您的请求中设置 userAgent Header 就足够了:

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()

这篇关于如何以编程方式在 Swift 中请求桌面站点(没有 UIWebView)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆