gpt4 book ai didi

ios - Swift - 如何在安装之前在应用程序中保存 json 文件

转载 作者:行者123 更新时间:2023-11-30 12:14:35 24 4
gpt4 key购买 nike

我对 iOS 还很陌生,所以我不知道解决我的问题的最佳解决方案:我使用 API 来获取我在应用程序中显示的数据(使用 Alamofire 发送请求并获取 json 文件)。我的问题是我不能依赖这个 API 来始终响应(API 创建者知道这个问题)。所以我正在考虑在我的应用程序中保存我需要的所有 json 文件(几十个)。这是最佳实践吗?如果是这样,我该怎么做?

最佳答案

您需要将您的应用程序与这些 plist 捆绑在一起。它将在第一次应用程序启动时可供您使用,但也会增加应用程序的大小(实际上取决于单个 plist 的大小)。

需要将plist复制到Bundle资源中。只需将它们添加到您的工作区/项目中即可。

这样,这些 plist 将与您的应用程序捆绑在一起,例如您的 .storyboard、.xib 文件和图像。另外,由于这些可以直接从您的 ipa 中读取,因此不要在这些 plist 中保留任何 secret 数据

enter image description here

之后,请确保只需检查 Target->BuildPhases-> Copy Bundle Resources。您的文件应该列在那里。 enter image description here

从捆绑的 plist 中读取数据 (Swift 3):

if let fileUrl = Bundle.main.url(forResource: "fileName", withExtension: "plist"),
let data = try? Data(contentsOf: fileUrl) {
if let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) {
print(result) // result is of type Any here, and needs to be converted to appropriate type(depends on plist root)
}
}

关于ios - Swift - 如何在安装之前在应用程序中保存 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com