Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get file name from URLSession.shared.data get request

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

  1. A filename specified using the content disposition header.
  2. The last path component of the URL.
  3. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading