0

First time working on an apple swift project. I am building a library where I send an HTTP request to an API and I need to retrieve the cookies that are returned in the response but for some reason they are not being retrieved.

Below is the code that I have.

let url = URL(string: "http://192.168.1.118:500/initialise")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let parameters: [String: String] = [
            "ApplicationID": app_id,
            "DeviceID": "123456",
            "AppVersion": app_version
        ]

        request.setValue(api_key, forHTTPHeaderField: "authorisation-token")

        //request.httpBody = parameters.percentEscaped().data(using: .utf8)
        let postString = self.getPostString(params: parameters)
        request.httpBody = postString.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) {data, response, error in
            guard let data = data,
            let response = response as? HTTPURLResponse,
                error == nil else {
                    print("error", error ?? "Unknown Error")
                    return
            }

            guard(200...299) ~= response.statusCode else {
                print("statusCode should 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }

            print ("HTTP Status Code: " + String(response.statusCode))

            print ("-------Cookies--------")

            let cookieStorage = HTTPCookieStorage.shared

            let cookies = cookieStorage.cookies(for: URL(string:"192.168.1.118:500")!) ?? []
            for cookie in cookies {

                if cookie.name == "SESSIONID" {
                    MyClass.SESSIONID = cookie.value
                }
                else if cookie.name == "DO-LB" {
                    MyClass.DOLB = cookie.value
                }
            }

I've tried changing the cookieStorage.cookies URL to include and the port number 500 and exclude it but unfortunately neither of which has worked.

Boardy
  • 35,417
  • 104
  • 256
  • 447
  • try one of the solution for here. It might help https://stackoverflow.com/questions/29596206/how-to-get-cookie-from-a-nsurlsession-with-swift – Viren Patel Oct 07 '19 at 19:08
  • Ah that sorted it, I did find that one myself, but misread it it had setCookies I was thinking it was sending a request with a cookie not getting the cookie from a request. – Boardy Oct 07 '19 at 21:02

0 Answers0