我正在使用NSURLSession下载文件。某些网站(如亚马逊)不在URL中使用文件名(例如:http://server/file.php?id=22)。我怎样才能获得这些文件名?
没有名称的示例网址:https://odesk-prod-att.s3.amazonaws.com/...oCtjM%3D
我正在使用这样的功能:
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
print("Download finished: \(location.absoluteString)")
}
// Download finished: file:///.../CFNetworkDownload_UTywas.tmp
答案 0 :(得分:5)
在创建自己的文件名之前检查建议的文件名:
downloadTask.response?.suggestedFilename
答案 1 :(得分:1)
终于找到了半解决方案。现在我正在检测文件的MIME并根据MIME类型重命名。
是:“abcd.tmp” 新:“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
}