小编典典

如何在Swift中将文件写入苹果文件应用程序中的文件夹

swift

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

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

阅读 786

收藏
2020-07-07

共1个答案

小编典典

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

您可以UIDocumentInteractionController用来共享位于应用程序捆绑包内,文档目录中或可从应用程序访问的另一个文件夹中的任何文件类型。

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
    }
}
2020-07-07