目前我有一个iOS应用程序可以从网站上提取价格和数据。到目前为止它一直运作良好,但我想让它更准确。为此,我需要为我当前正在使用String(contentsOf:_)的URL请求设置cookie。
let requestUrl: URL = URL(string: "http://www.samsclub.com/sams/search/searchResults.jsp?searchTerm=Apple")!
var content: String?
do {
content = try String(contentsOf: requestUrl)
} catch {
print("Error while converting an NSURL to String: \(error)")
}
if content != "" {
// I do things with the content of the requestUrl...
}
我想也许我应该使用Alamofire来拉这些网站,然后解析数据。
我需要设置更改商店编号的cookie进行搜索,但无法找到方法。 Bellow是我用来提取网站数据的代码,不用设置Cookie。
let requestUrl: String = "http://www.samsclub.com/sams/search/searchResults.jsp?searchTerm=Apple"
Alamofire.request(requestUrl, method: .post).responseString { response in
if let content: String = response.result.value {
// I do things with the content of the requestUrl...
}
}
我发现有许多不同的方法可以通过Alamofire设置不起作用的Cookie,但如果Alamofire不是这样做的,请通知我。我真的需要这个工作,我愿意接受任何建议。
答案 0 :(得分:10)
这一天花了四个星期,但我明白了! URLRequest
和Alamofire是我光荣的答案!
创建要调用的网址。
let requestUrl: String = "http://www.samsclub.com/sams/search/searchResults.jsp?searchTerm=Apple"
接下来使用URL字符串创建URLRequest
,并设置其http方法。
var urlRequest = URLRequest(url: requestUrl)
urlRequest.httpMethod = "POST"
然后为URLRequest
设置Cookie。
urlRequest.setValue("myPreferredClub=4969", forHTTPHeaderField: "Cookie")
urlRequest.httpShouldHandleCookies = true
最后发送URLRequest
Alamofire,并以我想要的方式使用响应数据。
Alamofire.request(urlRequest).responseString { response in
if let content: String = response.result.value {
// I do things with the content of the urlRequest...
}
}