I want to write a String to a file. If the file doesn't exist it should be created. If it does, the String should be appended.
I tried:
    let data = text.data(using: String.Encoding.utf8)
    let filemgr = FileManager.default
    let path = filemgr.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last?.appendingPathComponent("out.txt")
    if !filemgr.fileExists(atPath: (path?.absoluteString)!) {
        filemgr.createFile(atPath: (path?.absoluteString)!, contents: data, attributes: nil)
    } else {
        var file = FileHandle(forReadingAtPath: (path?.absoluteString)!)
        let databuffer = String(describing: file?.readDataToEndOfFile())
        file = FileHandle(forWritingAtPath: (path?.absoluteString)!)
        if file != nil {
            file?.seek(toFileOffset: 10)
            file?.write(data!)
            file?.closeFile()
        }
    }
so far the file doesn't even seem to get created, since it jumps to the createFile every time. what am I doing wrong?
Use (path?.path)! instead of (path?.absoluteString)!.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With