Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(Swift)如何检查内容编码是否为gzip_Swift_Http_Gzip - Fatal编程技术网

(Swift)如何检查内容编码是否为gzip

(Swift)如何检查内容编码是否为gzip,swift,http,gzip,Swift,Http,Gzip,Swift中是否有任何方法可以确定来自请求的数据是否返回gzip 我想编写一个测试方法来检查内容编码是否返回gzip文件: 如果读取文件的前4个字节,则应获得 因此,您应该能够执行以下操作: var magicNumber = [UInt](count: 4, repeatedValue: 0) data.getBytes(&magicNumber, length: 4 * sizeof(UInt)) 如果它是gzip,它将有一个神奇的数字1f8b,所以检查一下 您可以从HTTPURL

Swift中是否有任何方法可以确定来自请求的数据是否返回gzip

我想编写一个测试方法来检查内容编码是否返回gzip文件:

如果读取文件的前4个字节,则应获得

因此,您应该能够执行以下操作:

var magicNumber = [UInt](count: 4, repeatedValue: 0)
data.getBytes(&magicNumber, length: 4 * sizeof(UInt))

如果它是gzip,它将有一个神奇的数字1f8b,所以检查一下

您可以从
HTTPURLResponse
中的标题字段中获取此信息:

URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let response = response as? HTTPURLResponse {
        if let encoding = response.allHeaderFields["Content-Encoding"] as? String {
            print(encoding)
            print(encoding == "gzip")
        }
    }
}.resume()
请注意,这将下载标题和数据

如果只想获取标题而不下载数据,更好的解决方案是使用
URLRequest
设置为
“HEAD”
,如下所示:

var request = URLRequest(url: url)
request.httpMethod = "HEAD"

URLSession.shared.dataTask(with: request) { (_, response, _) in
    if let response = response as? HTTPURLResponse {
        if let enc = response.allHeaderFields["Content-Encoding"] as? String {
            print(enc)
            print(enc == "gzip")
        }
    }
}.resume()
这样,只下载标题