首页 > 解决方案 > 从 Swift 中的 HTTP 请求响应中检索 cookie

问题描述

第一次做苹果 swift 项目。我正在构建一个库,在其中向 API 发送 HTTP 请求,我需要检索响应中返回的 cookie,但由于某种原因,它们没有被检索到。

以下是我拥有的代码。

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

我尝试将 cookieStorage.cookies URL 更改为包含和端口号 500 并排除它,但不幸的是,这两个都不起作用。

标签: iosswift

解决方案


推荐阅读