为 URL 请求设置 Cookie

Set Cookies for URL Request

目前我有一个 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来搜索,但一直找不到方法。下面是我用来提取网站数据的代码 没有 设置 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 不是这种方法,请通知我。我真的需要它来工作,我愿意接受任何建议。

一天花了四个星期,但我想通了! URLRequest 和 Alamofire 是我出色的答案!

  1. 创建URL调用。

    let requestUrl: String = "http://www.samsclub.com/sams/search/searchResults.jsp?searchTerm=Apple"
    
  2. 接下来用 URL 字符串创建 URLRequest,并设置它的 http 方法。

    var urlRequest = URLRequest(url: requestUrl)
    urlRequest.httpMethod = "POST"
    
  3. 然后为URLRequest设置cookie。

    urlRequest.setValue("myPreferredClub=4969", forHTTPHeaderField: "Cookie")
    urlRequest.httpShouldHandleCookies = true
    
  4. 最后用 Alamofire 发送 URLRequest,并以我希望的任何方式使用响应数据。

    Alamofire.request(urlRequest).responseString { response in
        if let content: String = response.result.value {
            // I do things with the content of the urlRequest...
        }
    }