swift - 使用 URLSessionDownloadDelegate 获取 HTTP header

标签 swift nsurlsession

我如何从服务器获取 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/

相关文章:

swift - 每天午夜运行代码

ios - NSDictionary 到 NSString 不工作

ios - 什么是 UserNotification 框架相当于 didReceive 通知 : UILocalNotification?

swift - 在 Xcode 中检查 URL 文本作为字符串

ios - 将数据推送到 UITableView 未显示

ios - NSURLSession 任务文件下载发生在程序需要使用该文件之后

swift - NSURLSession dataTaskWithRequest completionHandler 获取 NSZeroData?

ios - NSURLSession:无法与后台传输服务通信

swift - 如何使用 URLSession 在异步 api 调用中查找哪个响应属于哪个请求

ios - 关闭侧面菜单