首页 > 解决方案 > 如何读取在本地 xcode 9、Swift 语言 4 中创建的(JSON 或 Txt 或 XMl 或 XML)文件

问题描述

如何通过 Xcode 以 swift 4 语言读取上述任何文件。

标签: xcodeswift4

解决方案


以下是如何读取名为“test.json”的本地 .json 文件:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
                    // do stuff
          }
      } catch {
           // handle error
      }
}

其中“test”是文件名,“json”是类型。您可以将 ofType: 参数替换为您想要的类型,例如“txt”、“xml”。

资料来源:使用 Swift 读取 JSON 文件


推荐阅读