如果使用文件管理器连接 USB,如何使用 Swift 3 在 USB 上保存 .txt 文件? (macOS 应用程序开发)
How do you save a .txt file using Swift 3 on a USB if it is connected using filemanager? (macOS app development)
这可能建立在提到的问题之上:
Read and write data from text file
我想做的是,如果连接了某种类型的可移动卷,可以选择将文件直接写入驱动器,如果可能的话,写入该驱动器的某个子文件夹。
这是我目前使用的代码:
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)
}
我知道检测可移动驱动器的唯一方法是使用磁盘仲裁框架。
好消息是我在 Apple 的时候确实为它写了一些最小的documentation。
坏消息是它是一个纯 C 框架 (Core Foundation),这使得即使在 Objective-C 中使用起来也很不愉快,更不用说 Swift.
这可能建立在提到的问题之上: Read and write data from text file
我想做的是,如果连接了某种类型的可移动卷,可以选择将文件直接写入驱动器,如果可能的话,写入该驱动器的某个子文件夹。
这是我目前使用的代码:
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)
}
我知道检测可移动驱动器的唯一方法是使用磁盘仲裁框架。
好消息是我在 Apple 的时候确实为它写了一些最小的documentation。
坏消息是它是一个纯 C 框架 (Core Foundation),这使得即使在 Objective-C 中使用起来也很不愉快,更不用说 Swift.