How to get cookie from a NSURLSession with Swift?

前端 未结 5 603
忘掉有多难
忘掉有多难 2020-12-13 10:04

I have a NSURLSession that calls dataTaskWithRequest in order to send a POST request in this way

func makeRequest(parameters: String, url:String){
    var po         


        
5条回答
  •  我在风中等你
    2020-12-13 11:06

    The Swift rendition might look something like:

    let task = session.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)")
        }
    }
    task.resume()
    

提交回复
热议问题