gpt4 book ai didi

json - Swift 将 key 添加到本地 JSON 以保存复选标记

转载 作者:行者123 更新时间:2023-11-30 11:30:56 29 4
gpt4 key购买 nike

我正在尝试在我的应用程序中保存复选标记。但是因为我的数据来自 api.. 我不知道如何添加像“checked”这样的键。问题是 JSON 每周下载一次,添加新内容。有没有办法仍然保存我的复选标记?

struct Base : Codable {
let expireDate : String
let Week : [Weeks]
}

struct Weeks : Codable {
let name : String
let items : [Items]
}

struct Items : Codable {
let Icon: String
let text : String
}

在我的 RootTableView 中,我有数组 Weeks,我想向子 tableView 项目添加复选标记。

提前致谢

更新:

  //
// Download JSON
//
enum Result<Value> {
case success(Value)
case failure(Error)
}

func getItems(for userId: Int, completion: ((Result<Base>) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "api.jsonbin.io"
print(NSLocale.preferredLanguages[0])

let preferredLanguage = NSLocale.preferredLanguages[0]
if preferredLanguage.starts(with: "de"){
urlComponents.path = "/b/xyz"
}
else
{
urlComponents.path = "/xyz"
}

let userIdItem = URLQueryItem(name: "userId", value: "\(userId)")
urlComponents.queryItems = [userIdItem]
guard let url = urlComponents.url else { fatalError("Could not create URL from components") }

var request = URLRequest(url: url)
request.httpMethod = "GET"


let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"secret-key": "xyzzy"
]

let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (responseData, response, responseError) in
DispatchQueue.main.async {
if let error = responseError {
completion?(.failure(error))
} else if let jsonDataItems = responseData {
let decoder = JSONDecoder()

do {
let items = try decoder.decode(Base.self, from: jsonDataItems)
completion?(.success(items))
} catch {
completion?(.failure(error))
}
} else {
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Data was not retrieved from request"]) as Error
completion?(.failure(error))
}
}
}

task.resume()
}


func loadJson() {
getItems(for: 1) { (result) in
switch result {
case .success(let item):
self.saveItemsToDisk(items: item)
self.defaults.set(item.expireDate, forKey: "LastUpdateItems")
case .failure(let error):
fatalError("error: \(error.localizedDescription)")
}
self.getItemesFromDisk()
}
}

//
// Save Json Local
//

func getDocumentsURL() -> URL {
if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
return url
} else {
fatalError("Could not retrieve documents directory")
}
}

func saveItemsToDisk(items: Base) {
// 1. Create a URL for documents-directory/items.json
let url = getDocumentsURL().appendingPathComponent("items.json")
// 2. Endcode our [Item] data to JSON Data
let encoder = JSONEncoder()
do {
let data = try encoder.encode(items)
// 3. Write this data to the url specified in step 1
try data.write(to: url, options: [])
} catch {
fatalError(error.localizedDescription)
}
}

func getItmesFromDisk(){
// 1. Create a url for documents-directory/items.json
let url = getDocumentsURL().appendingPathComponent("items.json")
let decoder = JSONDecoder()
do {
// 2. Retrieve the data on the file in this path (if there is any)
let data = try Data(contentsOf: url)
// 3. Decode an array of items from this Data
let items = try decoder.decode(Base.self, from: data)
itemsDisk = items
} catch {

}
}

最佳答案

我将为 Items 创建一个包装类(或结构),例如 MyItem,其中包含原始 Items 对象和复选标记属性。

class MyItem {
let item: Items
var checkmark: Bool
//more properties...?

init(withItem item: Items {
this.item = item
this.checkmark = false
}

func isEqual(otherItem item: Items) -> Bool {
return this.item == item
}
}

isEqual 用于检查是否已存在下载的 Items 对象的 MyItem 对象,或者是否应创建一个新对象。 isEqual 假设您更改 Items 结构以实现 Equatable 协议(protocol)。

您可能还需要替换 Weeks,但在这里您不需要包含原始 Weeks 对象。

class MyWeek {
let name: String
let items: [MyItem]
}

关于json - Swift 将 key 添加到本地 JSON 以保存复选标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50270180/

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