Set Cookies for URL Request

odonckers picture odonckers · Mar 23, 2017 · Viewed 13.5k times · Source

Currently I have an iOS app that pulls prices and data from websites. So far its been working well, but I want to make it more accurate. To do so, I need to set the cookies for the URL request that I'm currently using String(contentsOf: _) for.

Current Process

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...
}

Could Use?

I thought that maybe I should use Alamofire instead to pull those website, and then parse the data.

I need to set the cookie that changes the store number to search, but have been unable to find a way to do so. Bellow is the code I have for pulling the websites data without setting a 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...
    }
}

Other Claims

I have found many different ways to set cookies through Alamofire that don't work, but if Alamofire isn't the way to do it, please inform me. I really need this to work, and I'm open to any and every suggestion.

Answer

odonckers picture odonckers · Apr 20, 2017

It took four weeks to the day, but I figured it out! URLRequest and Alamofire were my glorious answers!

  1. Create the URL to call.

    let requestUrl: String = "http://www.samsclub.com/sams/search/searchResults.jsp?searchTerm=Apple"
    
  2. Next make the URLRequest with the URL string, and set its http method.

    var urlRequest = URLRequest(url: requestUrl)
    urlRequest.httpMethod = "POST"
    
  3. Then set the cookies for the URLRequest.

    urlRequest.setValue("myPreferredClub=4969", forHTTPHeaderField: "Cookie")
    urlRequest.httpShouldHandleCookies = true
    
  4. Finally send the URLRequest with Alamofire, and use the response data in whatever way I wish.

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