【问题标题】:How to read a text file while developing an ios app using xcode [duplicate]如何在使用 xcode 开发 ios 应用程序时读取文本文件 [重复]
【发布时间】:2018-12-23 13:22:59
【问题描述】:

我现在正在使用 xcode(Swift) 开发一个 iOS 应用程序。我想导入存储在文本文件中的数据,并在屏幕上显示文本文件中的单词。如何将现有文本文件导入项目?我应该安装什么吗?如何读取文本文件并将单词存储在数组中?

【问题讨论】:

  • 这个问题似乎与读取文本文件的 API 有关。这个问题似乎是关于如何首先使用 Xcode 使文本文件可用于 iOS 应用程序。

标签: ios swift xcode file text


【解决方案1】:

您可以在 iOS 中轻松读取文件。请按以下步骤操作:

第 1 步:将文件添加到项目中

第 2 步:读取文件

编辑

斯威夫特:

    let filePath = Bundle.main.path(forResource: "File", ofType: "txt");
    let URL = NSURL.fileURL(withPath: filePath!)

    do {
        let string = try String.init(contentsOf: URL)

        // use string here
        print("read: " + string)
    } catch  {
        print(error);
    }

目标-C:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSURL *url = [NSURL fileURLWithPath: filePath];
NSString *string = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

谢谢!

【讨论】:

  • 你知道 OP 清楚地将语言声明为 Swift。你的回答很有启发性,但是当给出 Swift 代码时,永远不可能是一个好的答案
  • @OOPer,我忘了注意。太感谢了。我更新了答案。
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多