I am getting CSV file from the server with URLSession.shared.data get request:
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.timeoutInterval = 10
request.allHTTPHeaderFields = httpHeaders
let (data, response) = try await URLSession.shared.data(for: request)
Receive file data as Swift Data, I am also need file name or somehow receive details about file name. I see file name in response:
{ Status Code: 200, Headers {
"Content-Disposition" = (
"attachment; filename=\"fileName.csv\""
);
but how I can get this?
Use URLResponse.suggestedFileName
.
let (data, response) = try await URLSession.shared.data(for: request)
print(response.suggestefFileName)
From the documentation,
Accessing this property attempts to generate a filename using the following information, in order:
- A filename specified using the content disposition header.
- The last path component of the URL.
- The host of the URL.
Number 1 is exactly what you are trying to get. If there is a Content-Disposition header, that is what will be used.