英文:
file does not get created in the application folder
问题
I am trying to create a simple text file in the application folder, as follows:
struct RegistrationView: View {
init() {
let fileURL = URL.documentsDirectory
.appending(path: "test.txt")
print(fileURL.absoluteString)
let test = FileManager.default.createFile(atPath: fileURL.absoluteString, contents: nil, attributes: nil)
print(test)
}
var body: some View {
Text("hello")
}
}
Unfortunately, the file does not get created at all and the value of the variable of test
is false.
What am I doing wrong?
英文:
I am trying to create a simple text file in the application folder, as follows:
struct RegistrationView: View {
init() {
let fileURL = URL.documentsDirectory
.appending(path: "test.txt")
print(fileURL.absoluteString)
let test = FileManager.default.createFile(atPath: fileURL.absoluteString, contents: nil, attributes: nil)
print(test)
}
var body: some View {
Text("hello")
}
}
Unfortunately, the file does not get created at all and the value of the variable of test
is false.
What am I doing wrong?
答案1
得分: 1
你需要将文件路径传递给createFile
方法,而不是URL字符串。请尝试以下方法。
struct RegistrationView: View {
init() {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsDirectory.appendingPathComponent("test.txt")
print(fileURL.path)
let test = FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
print(test)
}
var body: some View {
Text("hello")
}
}
英文:
You need to pass the file path to the createFile
method. Not the URL string. Try the following.
struct RegistrationView: View {
init() {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsDirectory.appendingPathComponent("test.txt")
print(fileURL.path)
let test = FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
print(test)
}
var body: some View {
Text("hello")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论