Swift URLSessionでHTTPレスポンスコードを取得する方法

SwiftでURLSessionのdataTask関数を使ってサーバー上のデータを取得する際にHTTPレスポンスコードを取得する必要がありました。 そのメモです。

URLSessionのdataTaskでHTTPレスポンスコードの取り方

dataTaskの完了Closureに渡される URLResponse を HTTPURLResponseにキャストして、statusCodeプロパティを参照します。

let url:URL = URL(string: "http://127.0.0.1:8080/sample.json")!
let task = URLSession.shared.dataTask(with: url){ data, response, error in
	if let error = error{
		print(error.localizedDescription)
		return
	}
	if let response = response as? HTTPURLResponse {
		print("response.statusCode = \(response.statusCode)")
	}
}
task.resume()

結果(statusCode)

response.statusCode = 200

URLResponseから取れる値のサンプル

他にもURLResponse から取れる値を取得してみました。

let url:URL = URL(string: "http://127.0.0.1:8080/sample.json")!
let task = URLSession.shared.dataTask(with: url){ data, response, error in
	if let error = error{
		print(error.localizedDescription)
		return
	}
	if let response = response as? HTTPURLResponse {
		
		// URLResponseのプロパティ
		print("response.url = \(String(describing:response.url))")
		print("response.mimeType = \(String(describing: response.mimeType))")
		print("response.expectedContentLength = \(response.expectedContentLength)")
		print("response.textEncodingName = \(String(describing: response.textEncodingName))")
		print("response.suggestedFilename = \(String(describing: response.suggestedFilename ))")


		// HTTPURLResponseのプロパティ
		print("response.statusCode = \(response.statusCode)")
		print("response.statusCode localizedString=\(HTTPURLResponse.localizedString(forStatusCode: response.statusCode))")

		for item in response.allHeaderFields{
			print("response.allHeaderFields[\"\(item.key)\"] = \(item.value)")
		}
	
	}

}
task.resume()

結果

response.url = Optional(http://127.0.0.1:8080/sample.json)
response.mimeType = Optional("application/json")
response.expectedContentLength = 6023
response.textEncodingName = Optional("utf-8")
response.suggestedFilename = Optional("sample.json")
response.statusCode = 200
response.statusCode localizedString=no error
response.allHeaderFields["Content-Type"] = application/json; charset=UTF-8
response.allHeaderFields["Connection"] = keep-alive
response.allHeaderFields["Content-Length"] = 6023
response.allHeaderFields["Etag"] = "8590971131-6023-"2017-10-14T01:30:55.538Z""
response.allHeaderFields["Last-Modified"] = Sat, 14 Oct 2017 01:30:55 GMT
response.allHeaderFields["Server"] = ecstatic-2.2.1
response.allHeaderFields["Date"] = Sun, 15 Oct 2017 07:30:09 GMT
response.allHeaderFields["Cache-Control"] = max-age=3600

レスポンスヘッダの中から"Content-Type"を取る場合です。

let contentType = response.allHeaderFields["Content-Type"] ?? ""
print("contentType=\(contentType)")

結果

contentType=application/json; charset=UTF-8

後記

レスポンスをちゃんと見てみようと思って試してみました。

参考

URLResponse - Foundation | Apple Developer Documentation HTTPURLResponse - Foundation | Apple Developer Documentation