OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 Swift 中将文件写入位于 Apple Files App 中的文件夹 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:07
标题: ios - 如何在 Swift 中将文件写入位于 Apple Files App 中的文件夹

我的 Xcode 项目中有一个 XML 文件,我首先尝试将其保存到磁盘,其次如何判断我是否已成功保存它?这是正确的方法吗?使用模拟器,我导航到 iOS 11 中的新"file"文件夹,但我没有看到它,但我不确定它是否应该在那里?

guard let path = Bundle.main.url(forResource: "sample", withExtension: "xml") else {print("NO URL"); return}
    let sample = try? Data(contentsOf: path)


print("sample XML = \(String(describing: sample?.debugDescription))")

//put xml file on the device
let filename = getDocumentsDirectory().appendingPathComponent("sample.xml")
do {
    try sample?.write(to: filename)
} catch {
    print("ERROR")
}

更新以包括我检查文件是否存在:

 //check if file exists
    let checkPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = URL(fileURLWithPath: checkPath)
let filePath = url.appendingPathComponent("sample.xml").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
    print("FILE AVAILABLE")
} else {
    print("FILE NOT AVAILABLE")
}



Best Answer-推荐答案


您可以使用 UIDocumentInteractionController 并让用户在您分享您的网址时选择他想要保存您的文件的位置。用户只需要选择保存到文件并选择保存要导出的文件的目录即可。

您可以使用 UIDocumentInteractionController 共享位于您的 App 包内、您的 Documents 目录或可从您的 App 访问的其他文件夹中的任何文件类型。

class ViewController: UIViewController {
    let documentInteractionController = UIDocumentInteractionController()
    func share(url: URL) {
        documentInteractionController.url = url
        documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
        documentInteractionController.name = url.localizedName ?? url.lastPathComponent
        documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
    }
    @IBAction func shareAction(_ sender: UIButton) {
        guard let url = URL(string: "https://www.ibm.com/support/knowledgecenter/SVU13_7.2.1/com.ibm.ismsaas.doc/reference/AssetsImportCompleteSample.csv?view=kc") else { return }
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else { return }
            let tmpURL = FileManager.default.temporaryDirectory
                .appendingPathComponent(response?.suggestedFilename ?? "fileName.csv")
            do {
                try data.write(to: tmpURL)
                DispatchQueue.main.async {
                    self.share(url: tmpURL)
                }
            } catch { 
                print(error)
            }

        }.resume()
    }
}

extension URL {
    var typeIdentifier: String? {
        return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
    }
    var localizedName: String? {
        return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
    }
}

编辑/更新:

如果您想公开位于 App Bundle 文档目录中的文件,您可以查看这篇文章 How can I display my App documents in the Files app for iPhone

关于ios - 如何在 Swift 中将文件写入位于 Apple Files App 中的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46972013/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4