在我的应用中,用户扫描条形码,然后从API获取有关产品的信息。
我想创建一个历史记录部分,用户可以在其中查看最近的10种产品。
API数据的结果存储在Result类型中,因此必须能够识别该结果才能显示在列表中。
结果是一种自定义数据类型,我正在使用该数据类型存储来自API调用的产品的详细信息。
结果
struct Result: Codable, Identifiable {
var id = UUID()
var description: String?
var brand: String?
var ingredients: String?
var image: String?
var upc_code: String?
var return_message: String?
var return_code: String?
enum CodingKeys: String, CodingKey {
case description, brand, ingredients, image, upc_code, return_message, return_code
}
}
此数据类型存储Result数组,我将其显示为列表
历史
struct History: Codable {
var results: [Result]
}
这是API调用:
func loadData(url: String, completion: @escaping (Error?, Result?) -> Void ) {
if let url = URL(string: url) {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {return}
do {
let defaults = UserDefaults.standard
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(data) {
var sizeCheck = defaults.object(forKey:"productHistory") as? [Data] ?? [Data]()
if (sizeCheck.count == 10) { //Check if there's more than 10 products already on the history list
sizeCheck.removeLast()
}
sizeCheck.append(encoded) //Add new product to list
defaults.set(sizeCheck, forKey: "productHistory") //Add new list to userDefaults
}
let decoder = JSONDecoder()
let result: Result = try decoder.decode(Result.self, from: data)
completion(nil, result) //Used elsewhere to display the scanned product after it's been added to the history list
}
catch let e {
print(e)
completion(e, nil)
}
}
task.resume()
}
}
这是我的视图,当按下按钮时,该视图显示列表中的最后10个产品。
最后10种产品应使用键productHistory
存储在UserDefaults中。这是通过API调用LoadData()
struct historyView: View {
@Binding var showingHistory: Bool
@State private var results = [Result]()
var body: some View {
let defaults = UserDefaults.standard
if let products = defaults.object(forKey: "productHistory") as? Data {
if let decodedResponse = try? JSONDecoder().decode(History.self, from: products) {
self.results = decodedResponse.results
}
}
return List(self.results, id: \.id) { item in
Text(item.description!)
}
}
}
据我了解,问题在于UserDefaults无法存储JSON数据。因此,当获取API数据时,我将数据按原样存储到userdefualts中。然后在需要时对其进行解码,例如将其存储在历史记录中或显示出来。
当前我得到一个空白列表,并且下面的if语句没有通过。
if let decodedResponse = try? JSONDecoder().decode(History.self, from: products) {
如果将URL粘贴到浏览器中,则为API的JSON数据:
编辑
这是我的APICall():
func callAPI() -> String {
if (scannedCode.barcode == "") {
return "noneScanned"
}
else {
let hashedValue = scannedCode.barcode.hashedValue("API ID")
//print(hashedValue!)
loadData(url: "URL") { error, result in
if let err = error {
self.APIresult = err.localizedDescription
print(APIresult)
//output error
}
else if (result?.ingredients == nil) {
DispatchQueue.main.async {
self.APIresult = "noIngredients"
}
}
else if (result?.description == nil) {
DispatchQueue.main.async {
self.APIresult = "noDescription"
}
}
else {
DispatchQueue.main.async {
self.APIresult = "success"
}
}
DispatchQueue.main.async {
product.result = result!
//updates view that show's the scanned product, as it's @Published
}
}
return APIresult
}
}
在本部分中,我想查找有关该产品的哪些数据并进行相应的处理。因此,使用上述解决方案,我会根据是否有图像或描述等返回不同的值...
使用vadian解决方案,我将其更改为:
loadData(url: "URL") { result in
switch result {
case .success(product):
print("success")
case .failure(error):
print("failure")
}
}
答案 0 :(得分:2)
如评论中所述,您将Data
和Result
混在一起
首先删除History
并将Result
重命名为Product
。我们将将Product
的数组保存到UserDefaults
struct Product: Codable, Identifiable {
var id = UUID()
var description: String?
var image: String?
var upc_code: String?
var return_message: String?
var return_code: String?
private enum CodingKeys: String, CodingKey {
case description, image, upc_code, return_message, return_code
}
}
在loadData
中,使用通用Result
类型作为闭包参数。收到数据后,将其解码到Product
实例,然后加载保存的数组,删除first(!)项(如有必要)追加新项,保存回数组并使用新的{{1 }}。在Product
情况下传递所有潜在的错误。
failure
并调用它
func loadData(url: String, completion: @escaping (Result<Product,Error>) -> Void ) {
guard let url = URL(string: url) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error { completion(.failure(error)); return }
do {
let decoder = JSONDecoder()
let product = try decoder.decode(Product.self, from: data!)
let defaults = UserDefaults.standard
var history = [Product]()
if let readData = defaults.data(forKey:"productHistory") {
do {
history = try decoder.decode([Product].self, from: readData)
if history.count == 10 { history.removeFirst() }
} catch { print(error) }
}
history.append(product)
let saveData = try JSONEncoder().encode(history)
defaults.set(saveData, forKey: "productHistory")
completion(.success(product))
}
catch {
print(error)
completion(.failure(error))
}
}
task.resume()
}
在loadData(url: "URL") { result in
switch result {
case .success(let product):
if product.ingredients == nil {
self.APIresult = "noIngredients"
} else if product.description == nil {
self.APIresult = "noDescription"
} else {
self.APIresult = "success"
}
product.result = product
case .failure(let error):
self.APIresult = error.localizedDescription
print(APIresult)
}
}
中(请使用大写字母开头的名称结构)从HistoryView
获取数据并解码UserDefaults
数组。
Product
注意:请注意,UUID没有被编码和保存。
请使用更多描述性的变量名。