2

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)
}
nayem
  • 7,285
  • 1
  • 33
  • 51
Hussein Esmail
  • 353
  • 5
  • 21
  • All of this code looks perfectly fine for writing files. I think the question *you're actually asking* is "how to detect a removable volume exists and what that path is"? – Michael Dautermann Aug 30 '17 at 00:41
  • Yes, that was the intended question. Sorry for any confusion. This code writes text files perfectly, but just to the documents folder. – Hussein Esmail Aug 30 '17 at 00:42

1 Answers1

3

The only way I'm aware of to detect removable drives is to use the Disk Arbitration Framework.

The good news is that I did write some minimal documentation for it back when I was at Apple.

The bad news is that it's a pure C framework (Core Foundation), which makes it really unpleasant to use even in Objective-C, much less Swift.

dgatwood
  • 10,129
  • 1
  • 28
  • 49