使用URLSessionDownloadDelegate获取HTTP标头

Fre*_*rik 2 nsurlsession swift

我怎么会去从服务器获取的标题来检查它的状态码200404等等?

我有一个代表班:

class DownloadDelegate : NSObject, URLSessionDelegate, URLSessionDownloadDelegate, URLSessionTaskDelegate {
    // Implementations of delegate methods:
    [...]didFinishDownloadingTo location: URL[...]
    [...]didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64[...]
}
Run Code Online (Sandbox Code Playgroud)

但是我不确定在哪里可以提取标题。

Fel*_*SFD 6

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

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

假设您使用的是HTTP / HTTPS,则可以将其强制转换为HTTPURLResponse

每当您发出HTTP请求时,您返回的NSURLResponse对象实际上就是HTTPURLResponse类的实例。

来源:URLResponse的API参考

HTTPURLResponse具有获取状态代码(statusCode)和所有标头字段为[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
}
Run Code Online (Sandbox Code Playgroud)