ios - swift 2 - 从应用程序主包读取文本文件时出现文件未找到错误

标签 ios swift nsbundle

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

谢谢

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

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

sFilePath: Optional("/Users/user115387/Library/Developer/CoreSimulator/Devices/F3866C2A-869A-4CE5-9936-C8BC0CC5CE0D/data/Containers/Bundle/Application/A98B6D45-1C9A-4049-86F1-9502D45836B0/TableViewDemo.app/savedinfo.txt")

error in reading file Error Domain=NSCocoaErrorDomain Code=260 "The file “savedinfo.txt")” couldn’t be opened because there is no such file."

最佳答案

这段代码对我有用:

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

        }
    }

关于ios - swift 2 - 从应用程序主包读取文本文件时出现文件未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34807951/

相关文章:

arrays - 快速计算数组数字输入?

iphone - 如何获取应用程序中给定目录中所有文件的文件名 NSArray?

ios - 仅当选择单元格时才显示 tableViewCell 中的对象

iphone - MPMoviePlayerViewController 立即关闭

ios - AppDelegate 中的本地通知问题

macos - Cocoa - 从非主包加载资源

ios - cordova ios 构建插件无法恢复

ios - 尝试根据标识符删除多个本地通知

ios - iOS应用程序中的youtube iFrame在全屏后导致半屏变黑