[英]retrieving and writing a file in iOS
I looked at many SO question where the user wanted to access a document in his app directory. 我看了很多SO问题,用户希望在其中访问其应用程序目录中的文档。 I am new to all of this and just want some clarification on the matter. 我对所有这些都是新手,只想对此事作一些澄清。 I am building an open-source content blocker for iOS 9. 我正在为iOS 9构建开源内容阻止程序。
You can see the file tree. 您可以看到文件树。 I wonder if it is possible to access the file called blockerList.json which is in the folder Adblock Content Blocker . 我想知道是否可以访问文件夹Adblock Content Blocker中的名为blockerList.json的文件。 My goal was to write the json file based on what the user want to build. 我的目标是根据用户要构建的内容编写json文件。 I need to be able to modify the content of this file. 我需要能够修改此文件的内容。 Is this possible or should I stop trying and leave it like that? 这是否可能,或者我应该停止尝试并让它那样吗?
Thanks for any help. 谢谢你的帮助。
Note : You have readonly permission for application's bundle file. 注意:您对应用程序的捆绑文件具有只读权限。
NSDocumentDirectory
with backup attribute. 首先将文件复制到具有备份属性的NSDocumentDirectory
。 Use refrerence copy file to document directory iphone and for How do I prevent files from being backed up to iCloud and iTunes? 使用参考副本文件记录目录iphone ,以及如何防止文件备份到iCloud和iTunes? The app bundle is readonly as @dan said. 该应用程序包是只读的,如@dan所说。 So you have to copy the file from bundle into the Document directory then you able to modify the file at anytime. 因此,您必须将文件从分发包复制到文档目录,然后才能随时修改文件。
Copy file into document like this: 将文件复制到文档中,如下所示:
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)
}
Hope this will help you! 希望这个能对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.