问题描述
下载文件的问题。
我正在尝试下载文件形式的网址,并将其推送到打开/共享模式。但是da数据会作为数据下载,如果我尝试将其保存到File应用程序中,它将保存一个名为Data的文件。
我只需要下载并共享原始扩展名的文件即可。就像file.extension。
AF.download(url).responseData { response in
if let preset = response.value {
let shareArray = [preset]
let activityViewController = UIActivityViewController(activityItems: shareArray,applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController,animated: true,completion: nil)
}
}
也尝试了此代码,但应用程序崩溃了:
if let url = URL(string: downloadURL!) {
let task = URLSession.shared.downloadTask(with: url) { localURL,urlResponse,error in
if let localURL = localURL {
let shareArray = [localURL]
let activityViewController = UIActivityViewController(activityItems: shareArray,applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController,completion: nil)
}
}
task.resume()
}
解决方法
那里的问题是您试图共享返回的临时文件。它具有一个dynamic UTI(统一类型标识符)。您需要获取url响应建议的文件名,然后重命名该文件。
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
extension URL {
var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
}
let url = URL(string: "https://i.stack.imgur.com/varL9.jpg")!
URLSession.shared.downloadTask(with: url) { location,response,error in
guard let location = location,let httpURLResponse = response as? HTTPURLResponse,httpURLResponse.statusCode == 200 else { return }
let fileName = httpURLResponse.suggestedFilename ?? httpURLResponse.url?.lastPathComponent ?? url.lastPathComponent
let destination = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
do {
if FileManager.default.fileExists(atPath: destination.path) {
try FileManager.default.removeItem(at: destination)
}
print("location",location.typeIdentifier ?? "no UTI") // location dyn.ah62d4rv4ge81k5pu
try FileManager.default.moveItem(at: location,to: destination)
print("destination",destination.typeIdentifier ?? "no UTI") // destination public.jpeg
} catch {
print(error)
}
}.resume()