xcode - 如何读取在本地 xcode 9、Swift 语言 4 中创建的(JSON 或 Txt 或 XMl 或 XML)文件
问题描述
如何通过 Xcode 以 swift 4 语言读取上述任何文件。
解决方案
以下是如何读取名为“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 文件
推荐阅读
- sql - 如何使用 DML 命令从两个不同的表中更新表中的列
- c++ - 错误:我的班级的“操作员>>”不匹配
- vb.net - 从文本中读取文件并创建循环
- tensorflow - 如何使用 TensorFlow 2 自定义 CNN 层,在 CNN 的密集层提供新输入
- javascript - 未捕获的类型错误:无法读取创建的 VueJ 中未定义的属性“0”
- php - 用户提交收据后删除购物车中的项目
- python - Python通过循环登录不同的帐户
- symfony - Symfony“fos_rest.request_body”转换器:不要反序列化嵌套的 DTO 类
- javascript - addEventListener 加载在 Firefox 上触发两次
- javascript - 这是处理 JavaScript (TypeScript) 模块的好解决方案吗?