【发布时间】:2021-10-14 20:03:15
【问题描述】:
我在尝试将文本文件写入我的 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"}。
【问题讨论】:
-
这是 MacOS 还是 iOS?您的代码在哪里报告了错误?