如何在 Swift 中访问包含在应用程序包中的文件? [英] How to access file included in app bundle in Swift?
问题描述
我知道有一些与此相关的问题,但它们在 Objective-C 中.
I know there are a few questions pertaining to this, but they're in Objective-C.
如何在实际 iPhone 上使用 Swift 访问我的应用中包含的 .txt
文件?我希望能够从中读取和写入.这里是我的项目文件,如果你想看一看.如有必要,我很乐意添加详细信息.
How can I access a .txt
file included in my app using Swift on an actual iPhone? I want to be able to read and write from it. Here are my project files if you want to take a look. I'm happy to add details if necessary.
推荐答案
只需在 app bundle 中搜索资源
Simply by searching in the app bundle for the resource
var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")
但是你不能写入它,因为它在应用资源目录中,你必须在文档目录中创建它才能写入
However you can't write to it because it is in the app resources directory and you have to create it in the document directory to write to it
var documentsDirectory: NSURL?
var fileURL: NSURL?
documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last!
fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")
if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
print("file exist")
}else{
print("file doesnt exist")
NSData().writeToURL(fileURL!,atomically:true)
}
现在您可以从 fileURL
编辑 - 2018 年 8 月 28 日
这是如何在 Swift 4.2
var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")
在文档目录中创建
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let fileURL = documentsDirectory.appendingPathComponent("file.txt")
do {
if try fileURL.checkResourceIsReachable() {
print("file exist")
} else {
print("file doesnt exist")
do {
try Data().write(to: fileURL)
} catch {
print("an error happened while creating the file")
}
}
} catch {
print("an error happened while checking for the file")
}
}
这篇关于如何在 Swift 中访问包含在应用程序包中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!