[英]When getting data from Firebase Firestore my SwiftUI application crashes with an error. What could this be caused by?
When I launch the application it does load the data but when it is building a model it crashes with the following error:当我启动应用程序时,它确实加载了数据,但是在构建模型时,它崩溃并显示以下错误:
The following code is from my GetIphonesData.swift class:以下代码来自我的 GetIphonesData.swift 类:
import Foundation
import Firebase
import Combine
class GetIphonesData : ObservableObject {
@Published var data = [Iphone]()
init() {
let db = Firestore.firestore()
db.collection("iphones").addSnapshotListener { (snap, err) in
DispatchQueue.main.async {
if let err = err {
print("Error getting documents: \(err)")
} else {
for i in snap!.documents {
let iphone = Iphone(id: i.documentID,
name: i.get("name") as! String,
models: i.get("model") as! String,
yearReleased: i.get("yearReleased") as! String,
storageVariants: i.get("storageVariants") as! String,
colors: i.get("colors") as! String,
batteryCapacity: i.get("batteryCapacity") as! String,
cameraResolution: i.get("cameraResolution") as! String,
screenSize: i.get("screenSize") as! String,
screenResolution: i.get("screenResolution") as! String,
sensors: i.get("sensors") as! String,
memory: i.get("memory") as! String)
self.data.append(iphone)
}
}
}
}
}
}
When I print the data it prints.当我打印它打印的数据时。 When I have 1 item in the database it works but once I add more items into the database it crashes.
当我在数据库中有 1 个项目时,它可以工作,但是一旦我将更多项目添加到数据库中,它就会崩溃。 Is there a fix to this or is there a reason to it at all?
有没有办法解决这个问题,或者有什么原因吗?
The return value of the below code is nil and hence it's unable to cast it as a string.以下代码的返回值为零,因此无法将其转换为字符串。
models: i.get("model") as! String,
Change the above to:将以上内容改为:
models: i.get("model") != nil ?? i.get("model") as! String : "",
(or) (或者)
models: i.get("model") as? String ?? "",
Hope that helps.希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.