我的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")
}
Run Code Online (Sandbox Code Playgroud)
更新以包括我检查文件是否存在:
//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 { …Run Code Online (Sandbox Code Playgroud)