试图在swift中将字符串写入txt文件

时间:2017-07-17 00:51:37

标签: ios swift

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文件仍为空。

1 个答案:

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