swift 2 - 从app main bundle读取文本文件时找不到文件错误

时间:2016-01-15 09:27:23

标签: ios swift nsbundle

我在我的项目中添加了一个简单的文本文件(savedinfo.txt),其中只包含一行文本。我需要从我的应用程序中读取文本。我这样做如下。但是,由于某些原因,即使sFilePath显示文件路径,它在读取时也找不到该文件。请参阅下面的调试消息。我使用的是最新的Xcode 7.2。

由于

let sFilePath = String(NSBundle.mainBundle().pathForResource("savedinfo", ofType: "txt")

let sText =  try NSString(contentsOfFile: sFilePath, encoding: NSUTF8StringEncoding)
  

sFilePath:可选(“/ Users / user115387 / Library / Developer / CoreSimulator / Devices / F3866C2A-869A-4CE5-9936-C8BC0CC5CE0D / data / Containers / Bundle / Application / A98B6D45-1C9A-4049-86F1-9502D45836B0 / TableViewDemo 。应用程序/ savedinfo.txt“)

     

读取文件时出错Error Domain = NSCocoaErrorDomain Code = 260“无法打开文件”savedinfo.txt“)”因为没有这样的文件。“

1 个答案:

答案 0 :(得分:0)

此代码适用于我:

        if let sFilePath = NSBundle.mainBundle().pathForResource("savedinfo", ofType: "txt") {
        do {
            let sText = try NSString(contentsOfFile: sFilePath, encoding: NSUTF8StringEncoding)
            print(sText)
        }catch {

        }
    }