快速调用URLSession登录身份验证POST请求,如何在API调用后获取和保存Cookie

时间:2019-12-10 07:01:49

标签: ios swift cookies nsurlsession

我有一个用于登录授权的API,我可以通过URLSession创建POST请求,但在API调用后无法打印/检索Cookie。我在POSTMAN中测试过,它可以正常工作,它返回cookie。

借助Cookie,我将在应用程序内创建其他API调用。有人可以帮助检索Cookie。

    func LoginAuth(UN:String, PW: String){
    let url = URL(string: "https://ie-cms-test.cfapps.eu10.hana.ondemand.com/api/login")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let parameters: [String: Any] = [
        "username": "\(UN)",
        "password": "\(PW)"
    ]
    request.httpBody = parameters.percentEscaped().data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard
            let url = response?.url,
            let httpResponse = response as? HTTPURLResponse,
            let fields = httpResponse.allHeaderFields as? [String: String]
            else { return }
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
        HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
        for cookie in cookies {
            var cookieProperties = [HTTPCookiePropertyKey: Any]()
            cookieProperties[.name] = cookie.name
            cookieProperties[.value] = cookie.value
            cookieProperties[.domain] = cookie.domain
            cookieProperties[.path] = cookie.path
            cookieProperties[.version] = cookie.version
            cookieProperties[.expires] = Date().addingTimeInterval(31536000)
            let newCookie = HTTPCookie(properties: cookieProperties)
            HTTPCookieStorage.shared.setCookie(newCookie!)
            print("name: \(cookie.name) value: \(cookie.value)")
        }

        let cookieName = "MYCOOKIE"//Tried again to print
        if let cookie = HTTPCookieStorage.shared.cookies?.first(where: { $0.name == cookieName }) {
            print("COOKIE NAME:: \(cookieName): \(cookie.value)")
        }
    }
    task.resume()
}
extension Dictionary {
    func percentEscaped() -> String {
        return map { (key, value) in
            let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            return escapedKey + "=" + escapedValue
            }
            .joined(separator: "&")
    }
}

请让我完善请求中的问题,以便在成功登录后检索Cookie。

0 个答案:

没有答案