我的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")
}
答案 0 :(得分:6)
您可以使用UIDocumentInteractionController,让用户在共享网址时选择要保存文件的位置。用户只需选择保存到文件并选择保存要导出的文件的目录。您可以使用UIDocumentInteractionController来共享位于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
}
}