我在嘗試將文本檔案寫入我的 Documents 檔案夾的子目錄時遇到問題。
我的代碼如下:
@objc func makeFileButtonTapped() {
print(#function)
let tempName = "test"
var tempRecurrance: String = ""
switch recurrentInt {
case 0:
tempRecurrance = "Never"
case 1:
tempRecurrance = "Sometimes"
case 2:
tempRecurrance = "Often"
default:
tempRecurrance = "Unknown"
}
fileName = tempName ".txt"
let tempTitle: String = "\n\Title: " titleString "\n\n"
let tempDate: String = "Date: " dateString "\n\n"
let tempRecurring: String = "Recurs: " tempRecurrance "\n\n\n\n"
myDocument = ""
myDocument.append(tempTitle)
myDocument.append(tempDate)
myDocument.append(tempRecurring)
saveToDirectory()
}
func saveToDirectory(){
print(#function)
let fileManager = FileManager.default
// Create subdirectory
do {
let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let myAppDirectoryURL = directoryURL.appendingPathComponent("MySubDirectory")
if !fileManager.fileExists(atPath: myAppDirectoryURL.path) {
try fileManager.createDirectory(at: myAppDirectoryURL, withIntermediateDirectories: true, attributes: nil)
print("New directory created.")
//print("dictionary already exists.")
}
// Create document
let documentURL = myAppDirectoryURL.appendingPathComponent (fileName)
try myDocument.write(to: documentURL, atomically: false, encoding: .utf8)
print("documentURL =", documentURL.path)
} catch {
print(error)
}
}
我收到一條控制臺訊息,該目錄{Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}.
uj5u.com熱心網友回復:
取消檢查檔案是否已經存在,if !fileManager.fileExists(atPath: myAppDirectoryURL.path)因為createDirectory如果在您withIntermediateDirectories設定為真時目錄已經存在,呼叫將不會產生錯誤。
您使用了一些不屬于問題的屬性,因此為了完整性,這是我對您的函式的測驗版本
func saveToDirectory(_ fileName: String, text: String) {
let fileManager = FileManager.default
do {
let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let myAppDirectoryURL = directoryURL.appendingPathComponent("MySubDirectory")
try fileManager.createDirectory(at: myAppDirectoryURL, withIntermediateDirectories: true, attributes: nil)
let documentURL = myAppDirectoryURL.appendingPathComponent (fileName)
try text.write(to: documentURL, atomically: true, encoding: .utf8)
} catch {
print(error)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/314769.html
下一篇:Swift中的自定義裁剪影像
