gpt4 book ai didi

swift - 使用 URLSessionDownloadDelegate 获取 HTTP header

转载 作者:可可西里 更新时间:2023-11-01 00:21:30 25 4
gpt4 key购买 nike

我如何从服务器获取 header 以检查状态代码是 200404 等?

我有一个委托(delegate)类:

class DownloadDelegate : NSObject, URLSessionDelegate, URLSessionDownloadDelegate, URLSessionTaskDelegate {
// Implementations of delegate methods:
[...]didFinishDownloadingTo location: URL[...]
[...]didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64[...]
}

但我不确定在哪里可以提取 header 。

最佳答案

urlSession(_:downloadTask:didFinishDownloadingTo:)为您提供 header 。

参数 downloadTask 有一个类型为 URLResponse 的属性 .response .

假设您使用的是 HTTP/HTTPS,这可以转换为 HTTPURLResponse .

Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the HTTPURLResponse class.

(Source: API Reference of URLResponse)

HTTPURLResponse 具有获取状态代码 (statusCode) 和所有 header 字段的属性,如 [AnyHashable: Any] (allHeaderFields )。

示例:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let response = downloadTask.response as? HTTPURLResponse else {
return //something went wrong
}

let status = response.statusCode
let completeHeader = response.allHeaderFields
}

关于swift - 使用 URLSessionDownloadDelegate 获取 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com