Get cookies from NSHTTPURLResponse

前端 未结 5 920
忘掉有多难
忘掉有多难 2020-12-16 20:02

I\'ve an extremely weird problem, I\'m requesting a URL and I want to get the cookies from it, I\'ve used this way to get the cookies:

- (void)connection:(NS         


        
5条回答
  •  清酒与你
    2020-12-16 20:30

    @biloshkurskyi.ss answer is spot on.

    I spent half a day trying to find out why some of my cookies were not appearing in my response.allHeaderFields on iOS but it was there on Android (using the same service).

    The reason is because some cookies are extracted in advance and stored in the shared cookie store. They will not appear in allHeaderFields.

    Here's the swift 3 version of the answer if anyone needs it:

    let request = URLRequest(url: myWebServiceUrl)
    let session = URLSession.shared
    let task = session.dataTask(with: request, completionHandler: {
        (data, response, error) in
        if let error = error {
            print("ERROR: \(error)")
        } else {
            print("RESPONSE: \(response)")
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("DATA: " + dataString)
            }
            for cookie in HTTPCookieStorage.shared.cookies! {
                print("EXTRACTED COOKIE: \(cookie)") //find your cookie here instead of httpUrlResponse.allHeaderFields
            }
        }
    })
    task.resume()
    

提交回复
热议问题