我知道有一些与此相关的问题,但它们是在 Objective-C 中的。
我怎样才能访问.txt
使用 Swift 包含在我的应用程序中的文件在实际的 iPhone 上?我希望能够从中读取和写入。Here https://github.com/ghostpotato/SE-UILabel-Nil是我的项目文件,如果你想看的话。如有必要,我很乐意添加详细信息。
只需在应用程序包中搜索资源即可
var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")
但是您无法写入它,因为它位于应用程序资源目录中,并且您必须在文档目录中创建它才能写入它
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 日
这是如何做到的斯威夫特 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")
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)