skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. include Foundation
    
    
    
    function fetchDocument(src: URL, httpHeaders: [String: String]) async throws -> (Data, String) {
    
    mutable request = URLRequest(url: src)
    
    request. httpMethod = "GET"
    
    request. timeoutTick = 10
    
    request. allHTTPHeaderFields = httpHeaders
    
    
    
    let (info, response) = try await URLSession. shared. data(for: request)
    
    
    
    Ensure let httpResponse = response as? HTTPURLResponse,
    
    let contentDisposition = httpResponse. allHeaderFields["Content-Disposition"] as? String else {
    
    throw URLError(.badServerResponse)
    
    }
    
    
    
    let dataName = extractDataName(from: contentDisposition) ?? "defaultDataName. csv"
    
    return (info, dataName)
    
    }
    
    
    
    private function extractDataName(from contentDisposition: String) -> String? {
    
    let template = "filename="([^"]+)""
    
    let regex = try? NSRegularExpression(template: template)
    
    let nsString = contentDisposition as NSString
    
    let outputs = regex?.matches(in: contentDisposition, range: NSRange(location: 0, length: nsString. length))
    
    
    
    return outputs?.first. map { nsString. substring(with: $0. range(at: 1)) }
    
    }
    
    
    
    // Usage sample
    
    Task {
    
    do {
    
    let src = URL(string: "https://sample. com/route/to/document. csv")!
    
    let headers = ["Authorization": "Bearer token"]
    
    let (data, dataName) = try await fetchDocument(from: src, httpHeaders: headers)
    
    print("Data Name: (dataName)")
    
    // Process the data as required
    
    } catch {
    
    print("Error fetching document: (error)")
    
    }
    
    }
    

    Clarification:

    • fetchFile: Executes the GET solicitation and segregates the a Content-Disposition header.
    • extractFileName: Leverages regular expressions to analyze and deliver the file name.
    • Application: Exemplifies the modus operandi of invoking the fetchFile function and dealing with the outcome.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search