gpt4 book ai didi

ios - 更新 Firestore 数据库导致 iOS 崩溃

转载 作者:行者123 更新时间:2023-11-28 14:53:08 25 4
gpt4 key购买 nike

当我用任何新字段更新 firebase firestore 数据库时,它会立即终止所有正在运行的应用程序,该应用程序使用以下代码中的 fatal error 数据。

我得到的错误是“fatalError:”无法使用字典 [(name: “test”, availability: “test”, category: “test”)]

我希望能够在不让应用程序崩溃的情况下更新它。如果发生这种情况,他们必须删除并重新安装该应用程序才能使其再次运行,所以我认为它以某种方式在本地存储数据,但我找不到位置。

我该怎么做才能在不崩溃的情况下重置数据或重新加载?

抛出错误的文件(加载表格数据时):

fileprivate func observeQuery() {
stopObserving()
guard let query = query else { return }
stopObserving()
listener = query.addSnapshotListener { [unowned self] (snapshot, error) in
guard let snapshot = snapshot else {
print("Error fetching snapshot results: \(error!)")
return
}
let models = snapshot.documents.map { (document) -> Restaurant in
if let model = Restaurant(dictionary: document.data()) {
return model
} else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type \(Restaurant.self) with dictionary \(document.data())")
}
}
self.restaurants = models
self.documents = snapshot.documents

if self.documents.count > 0 {
self.tableView.backgroundView = nil
} else {
self.tableView.backgroundView = self.backgroundView
}

self.tableView.reloadData()
}


}

Restaurant.swift 文件:

import Foundation 

struct Restaurant {

var name: String
var category: String // Could become an enum
var availability: String // from 1-3; could also be an enum
var description: String

var dictionary: [String: Any] {
return [
"name": name,
"category": category,
"availability": availability,
"description": description
]
}

}

extension Restaurant: DocumentSerializable {

//Cities is now availability
static let cities = [
"In Stock",
"Back Order",
"Out of Stock"
]

static let categories = [
"Rock", "Boulder", "Grass", "Trees", "Shrub", "Barrier"
]

init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let category = dictionary["category"] as? String,
let availability = dictionary["availability"] as? String,
let description = dictionary["description"] as? String
else { return nil }

self.init(name: name,
category: category,
availability: availability,
description: description
)
}

}

带有 Document.Serializable 代码的本地集合文件:

import FirebaseFirestore

// A type that can be initialized from a Firestore document.
protocol DocumentSerializable {
init?(dictionary: [String: Any])
}

final class LocalCollection<T: DocumentSerializable> {

private(set) var items: [T]
private(set) var documents: [DocumentSnapshot] = []
let query: Query

private let updateHandler: ([DocumentChange]) -> ()

private var listener: ListenerRegistration? {
didSet {
oldValue?.remove()
}
}

var count: Int {
return self.items.count
}

subscript(index: Int) -> T {
return self.items[index]
}

init(query: Query, updateHandler: @escaping ([DocumentChange]) -> ()) {
self.items = []
self.query = query
self.updateHandler = updateHandler
}

func index(of document: DocumentSnapshot) -> Int? {
for i in 0 ..< documents.count {
if documents[i].documentID == document.documentID {
return i
}
}

return nil
}

func listen() {
guard listener == nil else { return }
listener = query.addSnapshotListener { [unowned self] querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshot results: \(error!)")
return
}
let models = snapshot.documents.map { (document) -> T in
if let model = T(dictionary: document.data()) {
return model
} else {
// handle error
fatalError("Unable to initialize type \(T.self) with local dictionary \(document.data())")
}
}
self.items = models
self.documents = snapshot.documents
self.updateHandler(snapshot.documentChanges)
}
}

func stopListening() {
listener = nil
}

deinit {
stopListening()
}
}

最佳答案

fatalError: "Unable to initialize type Restaurant with dictionary [(name: "test", availability: "test", category: "test")]

看起来非常简单 - 该字典不包含足够的信息来创建 Restaurant 对象。

错误来自

if let model = Restaurant(dictionary: document.data()) {
return model
} else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type \(Restaurant.self) with dictionary \(document.data())")
}

因为你的初始化器返回一个 nil 值,来自:

init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let category = dictionary["category"] as? String,
let availability = dictionary["availability"] as? String,
let description = dictionary["description"] as? String
else { return nil }

self.init(name: name,
category: category,
availability: availability,
description: description
)
}

因为你的 guard 返回 nil 因为你在字典中没有 description 键。

要修复,要么在字典中放入一个描述键,要么更改您的初始化程序以在缺少该键时使用默认描述。


例如,这是您的初始化程序,重写为使用默认描述,用于当缺少描述条目时

init?(dictionary: [String : Any]) {
guard let name = dictionary["name"] as? String,
let category = dictionary["category"] as? String,
let availability = dictionary["availability"] as? String
else { return nil }

let description = dictionary["description"] as? String
let defaultDescription: String = description ?? "No Description"

self.init(name: name,
category: category,
availability: availability,
description: defaultDescription
)
}

关于ios - 更新 Firestore 数据库导致 iOS 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639811/

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