Vasily
Vasily

Reputation: 3790

Get filename from NSURLSession download

I'm using NSURLSession to download file. Some websites (like Amazon) don't use filenames in URL (like: http://server/file.php?id=22). How can I get that filenames?

Example URL without name: https://odesk-prod-att.s3.amazonaws.com/...oCtjM%3D

I'm using such function:

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    print("Download finished: \(location.absoluteString)")
}

// Download finished: file:///.../CFNetworkDownload_UTywas.tmp

Upvotes: 5

Views: 2442

Answers (2)

Vasily
Vasily

Reputation: 3790

Finally found semi-solution for that. Now I'm detecting MIME of file and renaming it according MIME type.

Was: "abcd.tmp" New: "your_prefix.png"

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    guard let mimeType = downloadTask.response?.MIMEType,
        let fileExtension = mimeTypeToExtension(mimeType) else {
        return
    }

    // Your file name is: "prefixYouWant.\(fileExtension)"
}

/// Converting MIME Type to extension (e.g.: jpg)
func mimeTypeToExtension(mimeType: String) -> String? {
    let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, nil)
    guard let fileUTI = uti?.takeRetainedValue(),
        let fileExtension = UTTypeCopyPreferredTagWithClass(fileUTI, kUTTagClassFilenameExtension) else { return nil }

    let extensionString = String(fileExtension.takeRetainedValue())
    return extensionString
}

Dont forget to import MobileCoreServices

Upvotes: 3

emp
emp

Reputation: 3488

Check for the suggested filename before creating your own:

downloadTask.response?.suggestedFilename

Upvotes: 13

Related Questions