【问题标题】:I cant read my text files from my application's Bundle我无法从我的应用程序包中读取我的文本文件
【发布时间】:2016-08-03 11:52:52
【问题描述】:

我曾经使用以下代码从我的应用程序包中读取文本文件。但是,无论我的应用程序如何,都找不到它们了。我 100% 确定我的所有文件都在 Assets.xcassets 中,我可以看到它们、编辑它们、将它们从一个目录转换到另一个目录。但是我的应用程序不想阅读它们,请告诉我我错过了什么!

这是我正在使用的程序...

func readBundle(file:String) -> String
{
    var res: String = ""
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "txt")
    {
        let fm = NSFileManager()
        let exists = fm.fileExistsAtPath(path)
        if(exists)
        {
            let c = fm.contentsAtPath(path)
            res = NSString(data: c!, encoding: NSUTF8StringEncoding) as! String
        }
    }
    return res
}

我是这样使用它的:

let res = readBundle("test")
print(res)

【问题讨论】:

标签: swift file text bundle nsfilemanager


【解决方案1】:

当在 XCAssets 中存储非图像文件时,你应该使用 NSDataAsset 来访问它们的内容

https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSDataAsset_Class/

func readBundle(file:String) -> String
{
    var res = ""
    if let asset = NSDataAsset(name: file) ,
        string = String(data:asset.data, encoding: NSUTF8StringEncoding){
        res = string
    }
    return res
}

【讨论】:

    【解决方案2】:

    在另一个选项“XCAssets”中,您可以在项目结构中创建一个单独的资源文件夹/组,而不是图像,检查它们是否存在于项目主要目标的构建阶段部分的Copy Bundle Resource

    如果您添加这样的资源,您当前的代码应该可以正常工作

    func readBundle(file:String) -> String
    {
        var res: String = ""
        if let path = NSBundle.mainBundle().pathForResource(file, ofType: "txt")
        {
           //you should be able to get the path
           //other code as you has written in the question
        }
        return res
    }
    

    【讨论】:

    • 我想要,但是由于我是新手,stackoverflow.com 不允许我这样做
    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多