swifthttp-headershttpresponsehttpresponsemessage

Reading custom httpHeader with HTTPURLResponse


let task = URLSession.shared.dataTask(with: url) { _, response, error in
        if let error {
            print(error.localizedDescription)
            return
        }
        if let response = response as? HTTPURLResponse {
            print(response.description)
            if let xUserSigned = response.allHeaderFields["X-User-Signed"] as? String {
                print("X-User-Signed: \(xUserSigned)")
            }
        }
        completion(true)
    }
    task.resume()

Im trying to read custom httpHeader response before I display the page I want to know if user is or is not signed so in my header is this field "X-User-Signed"(also I already tried case sensitivity), but when I print whole header response the field is not there. The frustrating thing is that I can see it on safari or chrome.

I tried already case sensitivity, cookies refresh, also setting safari user-agent, nothing works


Solution

  • Not sure why your code doesn't work with allHeaderFields, but it's documentation refers to this:

    HTTP headers are case insensitive. To simplify your code, URL Loading System canonicalizes certain header field names into their standard form. For example, if the server sends a content-length header, it’s automatically adjusted to be Content-Length. Because this property is a standard Swift dictionary, its keys are case-sensitive. To perform a case-insensitive header lookup, use the value(forHTTPHeaderField:) method instead.

    So can you try:

    if let xUserSigned = response.value(forHTTPHeaderField: "X-User-Signed") {
        print("X-User-Signed: \(xUserSigned)")
    }