无法将数据写入 iOS Swift 中的文件

Can not write data to file in iOS Swift

我在文档文件夹中手动创建了一个文件 amutha.txt。我试图将数据写入该文件。我使用的代码是

let string="Amuthapriya"
try string.write(to:fileName, atomically: true, encoding: String.Encoding.utf8)

正确执行意味着没有异常或错误。但是当我打开 amutha.txt 时,文件是空的。为什么字符串没有写在那个文件中?我在做什么错误? 我的代码是:

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

@objc func buttonPressed(sender:UIButton) {
    print(sender.titleLabel?.text)
    let documentUrl:URL = getDocumentsDirectory()
    let fileName=documentUrl.appendingPathComponent("priya.txt", isDirectory: false)
    let filePath=fileName.path
    print( FileManager.default.fileExists(atPath: filePath))
    do {
        let string="Amuthapriya"
        try string.write(to:fileName, atomically: true, encoding: String.Encoding.utf8)
        print("written successfully")
        print("filePath: \(filePath)") 
    } catch {

    }
}

只需尝试在控制台中打印文件路径,因为您正在查看错误的文件并检查该文件是否可用并检查内容

do {
        let string="Amuthapriya"
        try string.write(to:fileName, atomically: true, encoding: String.Encoding.utf8)
        print("written successfully")
        print("filePath: \(filePath)")  // check file here
    } catch {

    }

I manually created a file amutha.txt in the documents folder. But then When I open amutha.txt the file is empty.

但是文本正在写入 priya.txt

let fileName=documentUrl.appendingPathComponent("priya.txt", isDirectory: false)

所以你找错了文件。

(也不要从文件 URL 更改为文件路径字符串。仅使用文件 URL。)