iOS:如何写入项目中特定目录的文件?

标签 ios swift iphone file

我正在尝试将我在应用程序中收集的一些字符串输出到文本文件。

文本文件将始终存在于我的项目中,如下所示:

我试图用新的(多行)字符串覆盖文件中的所有内容:

func writeFile(){

let theFile: FileHandle? = FileHandle(forWritingAtPath: "./MyFiles/file.txt")

if theFile != nil { // This is always nil!!!
    let data = ("Some text\nline 2\nline3\n" as String).data(using: String.Encoding.utf8)

    // Write it to the file
    theFile?.write(data!)

    // Close the file
    theFile?.closeFile()
}
else {
    print("Writing failed.")
}

} // End file writing

但是,FileHandler 始终返回 nil。我怀疑这是因为我提供的路径和/或文件名不正确?

我已经用谷歌搜索了几个小时,堆栈溢出了......但仍然不知道如何解决这个问题。如何指定正确的位置和文件?

最佳答案

您无法在应用程序沙箱之外写入文件。每个 iOS 应用程序都有单独的目录 Document、Library、tmp 来存储数据。

func writeFile(){

    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentationDirectory,.userDomainMask,true)
    let theFile: FileHandle? = FileHandle(forWritingAtPath: "\(documentsPath)/MyFiles/file.txt")

    if theFile != nil { // This is always nil!!!
        let data = ("Some text\nline 2\nline3\n" as String).data(using: String.Encoding.utf8)

        // Write it to the file
        theFile?.write(data!)

        // Close the file
        theFile?.closeFile()
    }
    else {
        print("Writing failed.")
    }

} // End file writing

关于iOS:如何写入项目中特定目录的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42584086/

相关文章:

swift - 确定 Any.Type 是否可选

Swift:如何保存和加载具有 Userdefaults 中结构值的字典

iphone - iOS UIButton 如何制作这样漂亮的按钮?

ios - UIPageViewController 与多个 UIViewController 与标题和底栏

ios - Swift 委托(delegate)传递信息

ios - 将 Base64 字符串应用于 UIImageView 在 iOS Swift 2 中不起作用

iOS Firebase 身份验证域对用户可见

ios - iOS 10越狱环境下,使用dlopen system/library/framework报错

swift - 单例模式 init 调用一次

iphone - ios - 如何动态添加 View