ios - 在哪里存储开发人员为 IOS 应用程序生成的数据

标签 ios swift directory

我需要创建一些包含运行应用程序所需的大量数据的文本文件。现在我认为 Library 文件夹非常适合存储此类数据。我以编程方式在应用程序主视图的 viewDidLoad 方法中创建了子文件夹(我打算在其中存储数据文件)到库文件夹。所以这是我创建子文件夹之一的代码

    let filemgr = NSFileManager.defaultManager()
    let dirPaths = NSSearchPathForDirectoriesInDomains(.LibraryDirectory,.UserDomainMask, true)
    let libDir = dirPaths[0] as! String

    let newDir = (libDir as NSString).stringByAppendingPathComponent("subFolder1")

    //Create the sub-dir else throw error
    do {
        try filemgr.createDirectoryAtPath(newDir, withIntermediateDirectories: false, attributes: nil)
    } catch let error as NSError {
        NSLog("Unable to create directory \(error.debugDescription)")
    }

当我运行此代码时,我的子文件夹已成功创建,从我在 Library 文件夹中列出目录时列出的子文件夹可以看出这一点。现在,我删除了这段代码(因为它已经达到了它的目的),并尝试在另一台设备上再次构建应用程序,但新的子文件夹并没有像我预期的那样列在这台新设备上。我认为一旦创建,Library 文件夹中的任何文件/文件夹都会保留在该文件夹中(类似于在应用程序包中创建的文件),并且可用于安装了该应用程序的任何设备。显然我错了。那么我应该在哪里存储用户创建的文件/文件夹,我希望这些文件/文件夹在安装了该应用程序的每台设备上都可用?谢谢你的想法

最佳答案

假设您不能将这些文件包含在应用程序包中,那么 Library/Application Support/ 可能是放置它们的正确位置。您可以在那里自由创建自己的子目录,但需要检查它是否存在并根据需要在每台设备上创建它。

作为应用启动过程的一部分,检查您需要的目录和文件是否存在,并根据需要创建/更新它们。请记住,您的应用程序可能会启动并在 Application Support 中遇到来自应用程序先前版本的数据(如果用户刚刚安装了更新),因此您可能希望在每次应用程序启动时重复此检查以防您更改应用程序版本之间所需的数据文件集。

由于您显然可以重新创建此数据,因此您还需要将其从用户备份中排除。查看File System Programming Guide

  • Put app-created support files in the Library/Application Support/ directory. In general, this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files, configuration files, templates and modified versions of resources loaded from the app bundle.
  • Remember that files in Documents/ and Application Support/ are backed up by default. You can exclude files from the backup by calling -[NSURL setResourceValue:forKey:error:] using the NSURLIsExcludedFromBackupKey key. Any file that can be re-created or downloaded must be excluded from the backup. This is particularly important for large media files. If your application downloads video or audio files, make sure they are not included in the backup.

关于ios - 在哪里存储开发人员为 IOS 应用程序生成的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38557808/

相关文章:

ios - RxDataSources 单元重新加载动画无法正常工作

ios - 获取接触点位置

swift - 表格 View 图像内容选择颜色

swift - 协议(protocol)默认实现可以覆盖方法吗?

ios - SwiftUI:如何检测列表何时滚动?

javascript - Node js 通过 HTTP 下载文件夹

java - 列出从 src 文件夹开始的文件

ios - UIWebView捏缩放以增加字体大小?

javascript - AngularJS - 检查文件夹是否存在

ios - 将图像放置在谷歌地图标记图标内