Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 正在尝试将字符串写入swift中的txt文件_Ios_Swift - Fatal编程技术网

Ios 正在尝试将字符串写入swift中的txt文件

Ios 正在尝试将字符串写入swift中的txt文件,ios,swift,Ios,Swift,我想将文本放入已放入项目文件夹的txt文件中,但运行代码后,Test.txt文件仍然为空。请查看上面的文档链接。有几个地方可以编写文件,这只是其中之一: import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Save data to file let path = Bundle.

我想将文本放入已放入项目文件夹的txt文件中,但运行代码后,Test.txt文件仍然为空。

请查看上面的文档链接。有几个地方可以编写文件,这只是其中之一:

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

应用程序的资源包是只读的。如何修复它?将该文件写入应用程序沙箱中的可写文件夹。我已经将test.txt文件放在我的项目中,不是可写的吗?您不能写入只读包资源(包含在应用程序中),您可以改为写入
应用程序支持
#seemore:所以我需要创建另一个函数?它说类型“String”的值没有成员“stringbyAppendingPathComponet”no。只需用这些替换您的行即可。重要的部分是获取路径,它不是“stringbyAppendingPathComponent”,而是“stringbyAppendingPathComponent”。您使用的是什么版本的Swift?我也在使用3.23.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")
        }