在Swift 5中创建和写入子目录的问题



我在尝试将文本文件写入文档文件夹的子目录时遇到问题。

我的代码如下:
@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 = "nTitle: " + titleString + "nn"
let tempDate: String = "Date: " + dateString + "nn"
let tempRecurring: String = "Recurs: " + tempRecurrance + "nnnn"


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"}.

删除检查文件是否已经存在,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)
}
}

相关内容

  • 没有找到相关文章

最新更新