【问题标题】:Download file with right extension下载具有正确扩展名的文件
【发布时间】:2021-01-25 20:34:27
【问题描述】:

下载文件有问题。

我正在尝试下载文件表单 url 并将其推送到打开/共享模式。但是 da 数据作为数据下载,如果我尝试将其保存到文件应用程序,它会保存一个名为数据的文件。

我只需要下载并共享带有原始扩展名的文件。喜欢 file.extension。

这里是代码使用。我在这里使用了 Alamofire pod:

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, animated: true, completion: nil)
        }
    }

    task.resume()
}

【问题讨论】:

    标签: ios swift uitableview alamofire


    【解决方案1】:

    问题在于您正在尝试共享返回的临时文件。它有一个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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多