【问题标题】:retrieving and writing a file in iOS在 iOS 中检索和写入文件
【发布时间】:2015-08-14 15:00:25
【问题描述】:

我查看了许多用户想要访问其应用目录中的文档的 SO 问题。我对这一切都很陌生,只想对此事进行一些澄清。我正在为 iOS 9 构建一个开源 content blocker

您可以看到文件树。我想知道是否可以访问文件夹 Adblock Content Blocker 中名为 blockerList.json 的文件。我的目标是根据用户想要构建的内容编写 json 文件。我需要能够修改这个文件的内容。这是可能的吗,还是我应该停止尝试并保持这种状态?

感谢您的帮助。

【问题讨论】:

  • 第一次启动应用程序时,您必须将文件复制到文档目录中。您无法写入应用程序包中的文件。
  • 不清楚何时更改文件,在构建时或在 iOS 设备上安装应用程序之后?
  • 我想在iOS设备上安装应用后编辑文件。

标签: ios ios9 file-writing


【解决方案1】:

正如@dan 所说,应用程序包是只读的。因此,您必须将文件从 bundle 复制到 Document 目录中,然后您才能随时修改文件。

像这样将文件复制到文档中:

class func copyFile(fileName: String) {
    let destPath: String = getPathInDocument(fileName)
    var fromPath = NSBundle.mainBundle().pathForResource("blockerList", ofType: "json")!

    var fileManager = NSFileManager.defaultManager()
    if !fileManager.fileExistsAtPath(destPath) {
        fileManager.copyItemAtPath(fromPath, toPath: destPath, error: nil)
    } else {
        println("The file allready exists at path:\(destPath)")
    }

}

class func getPathInDocument(fileName: String) -> String {
    return NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0].stringByAppendingPathComponent(fileName)
}

希望对您有所帮助!

【讨论】:

  • 修改会影响原来的json文件吗?
  • 如果原始 json 文件在 bundle 中,您将无法修改它。相反,您可以修改 Document 目录中的文件。
  • 您认为有一种方法可以在应用程序中包含 json 以便对其进行编辑吗?在应用程序中我只是load this json to make the content blocker。如果我在应用程序中生成 json 然后加载它,是否认为它会起作用?对于菜鸟问题​​,我很抱歉,我刚刚开始 iOS 开发。
  • 我认为这是不可能的。也许这会对你有所帮助:stackoverflow.com/questions/12679448/…
  • 那么用户打开应用时不可能生成文件,根据他想要阻止的内容修改.json的内容?之后我们可以加载 json 并创建阻塞器
【解决方案2】:

注意:您对应用程序的捆绑文件具有只读权限。

  1. 首先将文件复制到NSDocumentDirectory,并带有备份属性。使用参考 copy file to document directory iphoneHow do I prevent files from being backed up to iCloud and iTunes?
  2. 检查引用 ImportingJSONFileY6JSONFileManager-iOS 以读取和写入 JSON 文件中的更改。

【讨论】:

  • 那个项目“Y6JSONFileManager-iOS”没有做太多,错误处理是这样的评论:“// TODO:处理错误”。
  • 修改会影响原始json文件吗?
  • 它会影响文档目录中的复制文件。
猜你喜欢
  • 2016-06-13
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多