odo*_*ers 1 cookies url urlrequest alamofire swift3
目前我有一个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...
}
Run Code Online (Sandbox Code Playgroud)
我想也许我应该使用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...
}
}
Run Code Online (Sandbox Code Playgroud)
我发现许多不同的方法通过Alamofire设置cookie不起作用,但如果Alamofire不是这样做的,请通知我.我真的需要这个工作,我对任何建议都持开放态度.
odo*_*ers 10
这一天花了四个星期,但我想通了!URLRequest
和Alamofire是我光荣的答案!
创建要调用的URL.
let requestUrl: String = "http://www.samsclub.com/sams/search/searchResults.jsp?searchTerm=Apple"
Run Code Online (Sandbox Code Playgroud)接下来URLRequest
使用URL字符串,并设置其http方法.
var urlRequest = URLRequest(url: requestUrl)
urlRequest.httpMethod = "POST"
Run Code Online (Sandbox Code Playgroud)然后设置cookie的URLRequest
.
urlRequest.setValue("myPreferredClub=4969", forHTTPHeaderField: "Cookie")
urlRequest.httpShouldHandleCookies = true
Run Code Online (Sandbox Code Playgroud)最后发送URLRequest
Alamofire,并以我想要的任何方式使用响应数据.
Alamofire.request(urlRequest).responseString { response in
if let content: String = response.result.value {
// I do things with the content of the urlRequest...
}
}
Run Code Online (Sandbox Code Playgroud)