如何访问Swift中应用程序捆绑包中包含的文件? [英] How to access file included in app bundle in Swift?

查看:80
本文介绍了如何访问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.

推荐答案

只需在应用程序包中搜索资源

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆