Ios 如何使用Alamofire Swift读取内容长度的HTTPResponse

Ios 如何使用Alamofire Swift读取内容长度的HTTPResponse,ios,swift,alamofire,httpresponse,Ios,Swift,Alamofire,Httpresponse,我试图从响应中读取内容长度,但它总是跳过并没有得到响应。即使是最简单的一个。我使用了不同的URL链接来检查,但每次跳过的结果都是一样的,并没有响应 甚至可以使用任何URL链接功能跳过 URL链接: calculateLength(链接:“”) 代码: 从服务器获取响应: (Response) <NSHTTPURLResponse: 0x6000000c7120> { URL: } { Status Code: 200, Headers { "Cache-Control"

我试图从响应中读取
内容长度
,但它总是跳过并没有得到响应。即使是最简单的一个。我使用了不同的URL链接来检查,但每次跳过的结果都是一样的,并没有响应

  • 甚至可以使用任何URL链接功能跳过
URL链接: calculateLength(链接:“”)

代码:

从服务器获取响应:

(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"
    );
} }

(响应){URL:}{状态代码:200,标题{
“缓存控制”=(
私有的
);
“内容编码”=(
gzip
);
“内容长度”=(
837
);
“内容类型”=(
“文本/html”
);
日期=(
“2020年5月21日星期四08:04:55 GMT”
);
服务器=(
“Microsoft IIS/8.5”
);
“设置Cookie”=(
“aspsessionidsscsccbab=AKDPKPMCKNDJPANFODFAJKAH;路径=/”
);
变化=(
“接受编码”
);
“X-Powered-By”=(
“ASP.NET”
);
} }

对于Alamofire 5,您的函数如下所示:

func calculateLength(link: String) {
     AF.request(link, method: .get).response() { response in
         if let headers = response.response?.headers  {
             print(headers.value(for: "Content-Length"))
         }
     }
}
对于Alamofire 4来说,可能是这样的

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)
             }
         }
     }
}

根据iOS版本,访问
httpurresponse
的属性
值(适用于iOS 13及以上版本)或
allHeaderFields
。 您只需传递密钥名,在您的情况下,它是
“Content Length”

扩展HTTPURLResponse{ func valueForHeaderField(headerField:String)->String{ 如果可用(iOS 13.0,*){ 返回值(用于HttpHeaderField:headerField) }否则{ 返回(所有HeaderFields作为NSDictionary)[headerField]作为?字符串 } } }
你可以调用上面的函数,比如

let contentLegth=response.response.valueForHeaderField(“内容长度”)

可能是因为内容长度为Int,所以您的演员阵容
为?String
失败?@serg_zhd即使我在
上设置了断点,如果让ALLheader=response.response?.allHeaderFields
它仍然会跳过,并且响应不会出现。请尝试从请求中删除
。responseJSON
-您会得到一个空的正文,并且在某些情况下响应字段被设置为零reason@serg_zhd试过了,但没用跳过。甚至我也使用了不同的URL
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)
             }
         }
     }
}