This may be building upon the question mentioned: Read and write data from text file
What I am trying to do, is if a certain type of removable volume is connected, have the option of writing the file directly on the drive, and if possible in a certain subfolder in that drive.
Here is the code I am currently using:
let fileManager = FileManager.default
var Extension: String = "txt"
let FileName: String = "TestFileName"
var DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(FileName).appendingPathExtension(Extension)
print("FilePath: \(fileURL.path)")
let DocumentIntro = "This text will be on the text file\n"
do {
// Write to the file
try DocumentIntro.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
var FileContents = "" // Used to store the file contents
do {
// Read the file contents
FileContents = try String(contentsOf: fileURL)
} catch let error as NSError
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}