iosswifturlsession

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?


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.