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 how do I do this now that write(_:)
is deprecated?
@available(macOS, introduced: 10.0, deprecated: 100000)
. According to the discussion at forums.swift.org/t/… that means deprecation in “some future version of the OS or Swift.” – Disbud