Search code examples
iosswift3filehandle

Problems when writing to file with FileHandler


I have a code that looks like this:

let fileName = "name.txt"
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
try! "".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
let fileHandle = try! FileHandle(forWritingTo: fileURL)
fileHandle.seekToEndOfFile()

And this code works. But if i remove the line:

try! "".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)

I get runtime exception. I am not sure why this line is needed?


Solution

  • If you look into the docs for FileHandle(forWritingTo:), the return value is specified as:

    The initialized file handle object or nil if no file exists at url.

    The file has to exist, otherwise nil is returned.

    The

    try! "".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
    

    creates the file.

    If you don't create the file and the file does not exist, trying to open the file using FileHandle will crash the app.

    The code would be probably more readable, if you created the file explicitly:

    FileManager.default.createFile(atPath: fileURL.path, contents: nil)