import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Save data to file
let path = Bundle.main.path(forResource: "Test", ofType: "txt")
let fileURL = URL(fileURLWithPath: path!)
let text = "write this\n and this"
do {
try text.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("error")
}
}
}
我想将文本放入已放入项目文件夹的txt文件中,但在运行代码后,Test.txt文件仍为空。
答案 0 :(得分:2)
请查看上面的文档链接。有几个地方你可以写文件,这只是其中之一:
let userDocumentsFolder = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let path = userDocumentsFolder.stringByAppendingPathComponent("Test.txt")
let fileURL = URL(fileURLWithPath: path)
let text = "write this\n and this"
do {
try text.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("error")
}