文件未在应用程序文件夹中创建。

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月10日 18:19:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定