4

I'm new to Swift and trying to append a string to a text file in iOS app.

string.write is simple enough, but will overwrite the existing info.

write(toFile: atomically:encoding:) also overwrites existing info, though the docs note that it may be extended in the future to allow adding information.

Using FileHandle seems logical, but the methods for writing to a file -- such as init(forWritingTo:) -- require write(_:), and that function is deprecated! The docs do not suggest an alternative or replacement.

    let fileName: String = "mytextfile.txt"
    let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let newFileUrl = directoryURL!.appendingPathComponent(fileName)
    let textToAdd = "Help me, Obiwan!"
    if let fileUpdater = try? FileHandle(forUpdating: newFileUrl) {
           fileUpdater.seekToEndOfFile()
           fileUpdater.write(textToAdd.data(using: .utf8)!)
           fileUpdater.closeFile()
        }

So what is the recommended way to do something like this now that write(_:) is deprecated?

Greg
  • 41
  • 3
  • Did you check the updates to https://stackoverflow.com/q/27327067/1187415? – Martin R Jan 13 '21 at 17:48
  • Yes. (And many others!) All of those answers use fileHandle.write, which the apple docs linked in the question show as deprecated. Am I wrong in assuming I shouldn't be using something marked as deprecated? – Greg Jan 13 '21 at 17:57
  • 2
    Indeed, the online documentation marks it as deprecated, but my Xcode does not show a warning. With "Jump to Definition” in Xcode one sees that the method is annotated as `@available(macOS, introduced: 10.0, deprecated: 100000)`. According to the discussion at https://forums.swift.org/t/dont-see-any-deprecation-warning-due-to-deprecated-100000-0-whats-the-rationale-for-marking-it-this-way/38404 that means deprecation in “some future version of the OS or Swift.” – Martin R Jan 13 '21 at 18:01
  • I likely wouldn't have noticed, but I'm new to Swift so I've been checking documentation as I go. Perhaps they'll take it out when that functionality is added to write(toFile: atomically:encoding:). I'll use .write for now. Thanks for the sanity check. – Greg Jan 13 '21 at 18:05
  • This did not work for me. I have found many examples, but so far I have not found any Swift code that actually appends an existing textfile. – K17 Dec 14 '22 at 20:42

0 Answers0