如何将文件写入位于 Swift 中 Apple Files App 的文件夹中 [英] How to write a file to a folder located at Apple's Files App in Swift

查看:45
本文介绍了如何将文件写入位于 Swift 中 Apple Files App 的文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an XML file in my Xcode Project, and I'm trying to first save it to disk, and secondly how can I tell if I've successfully saved it? Is this the proper approach? Using the simulator I navigated to the new "Files" folder in iOS 11 and I don't see it but I'm not sure if it should be there or not?

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")
}

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

updated to include my check if file exists:

 //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")
}

推荐答案

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

You can use UIDocumentInteractionController and let the user select where he wants to save your file when you share your url. The user just needs to select save to files and choose which directory to save the file you are exporting.

您可以使用 UIDocumentInteractionController 共享位于您的应用程序包内、文档目录或其他可从您的应用程序访问的文件夹中的任何文件类型.

You can use UIDocumentInteractionController to share any file type located inside your App bundle, at your Documents directory or another folder accessible from your 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
    }
}

这篇关于如何将文件写入位于 Swift 中 Apple Files App 的文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆