How to read Content-Length HTTPResponse with Alamofire Swift

Viewed 1973

I am trying to read Content-Length from the response but it always skips and not get response. Even its the simple one. I have used different URL link to check but result is same every time skips and there is no response.

  • Even can use any URL link function skips.

URL link: calculateLength(Link: "")

Code:

func calculateLength(Link: String)  {
        Alamofire.request(Link, method: .get, parameters: nil, encoding: URLEncoding.httpBody).responseJSON
                    { response in
                        //to get JSON return value
                        if let ALLheader = response.response?.allHeaderFields  {
                            if let header = ALLheader as? [String : Any] {
                                if let contentLength = header["Content-Length"] as? String {

                                }
                            }
                        }
        }
    }

Response Getting from Server:

(Response) <NSHTTPURLResponse: 0x6000000c7120> { URL:  } { Status Code: 200, Headers {
    "Cache-Control" =     (
        private
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        837
    );
    "Content-Type" =     (
        "text/html"
    );
    Date =     (
        "Thu, 21 May 2020 08:04:55 GMT"
    );
    Server =     (
        "Microsoft-IIS/8.5"
    );
    "Set-Cookie" =     (
        "ASPSESSIONIDSSSCCBAB=AKDPKPMCKNDJPANFODFAJKAH; path=/"
    );
    Vary =     (
        "Accept-Encoding"
    );
    "X-Powered-By" =     (
        "ASP.NET"
    );
} }

2 Answers

For Alamofire 5 your function would look like this:

func calculateLength(link: String) {
     AF.request(link, method: .get).response() { response in
         if let headers = response.response?.headers  {
             print(headers.value(for: "Content-Length"))
         }
     }
}

For Alamofire 4 it would be something like that

func calculateLength(link: String) {
     Alamofire.request(link, method: .get).responseJSON { response in
         if let headers = response.response?.allHeaderFields as? [String : Any] {
             if let contentLength = headers["Content-Length"] as? String {
                 print(contentLength)
             }
         }
     }
}

Access the HTTPURLResponse's property value (available for iOS 13 and above) or allHeaderFields as per the iOS version. You just have to pass the key name, which is "Content-Length" in your case.

extension HTTPURLResponse {
    func valueForHeaderField(_ headerField: String) -> String? {
        if #available(iOS 13.0, *) {
            return value(forHTTPHeaderField: headerField)
        } else {
            return (allHeaderFields as NSDictionary)[headerField] as? String
        }
    }
}

And you can call the above function like,

let contentLegth = response.response.valueForHeaderField("Content-Length")
Related