-1

I manually created a file amutha.txt in the documents folder. I tried to write data to that file. code which I used is

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

This is executed correctly means having no exceptions or errors. But then When I open amutha.txt the file is empty. Why the string is not written in that file? What Mistake I am doing? My code is:

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 {

    }
}
Sayooj
  • 375
  • 3
  • 13
Priya Sri
  • 145
  • 13

2 Answers2

1

Just try to print path of your file in console because you are watching wrong file and check that file if it is available there or not and check content

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 {

    }
Kishan Bhatiya
  • 2,175
  • 8
  • 14
0

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

But the text is being written to priya.txt.

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

So you are looking in the wrong file.

(Also do not change from file URL to file path string. Use file URL only.)

matt
  • 515,959
  • 87
  • 875
  • 1,141