gpt4 book ai didi

ios - 使用 Firebase ios 获取数据

转载 作者:行者123 更新时间:2023-11-28 15:59:10 24 4
gpt4 key购买 nike

我在 Android 中有一个应用程序,我正在构建它的 iOS 版本,但是当我尝试将用户数据提取到我的模型类中时,我收到一个错误,我知道这是因为有些节点内部没有所有键,但这在 Android 上没问题,我不知道如何在 Swift 3 上处理它。你可以在本文末尾的链接上看到我的数据。

我得到这个做一个.childadded:

Fatal error: unexpectedly found nil while unwrapping an Optional value

这是我的模型类:

struct User {
var name: String
var age: String
var gender: String
var description: String
var hair:String
var skin:String
var tel:String

init(name: String, age: String, gender: String, hair: String, skin: String, tel: String, description: String) {
self.name = name
self.age = age
self.gender = gender
self.description = description
self.hair = hair
self.skin = skin
self.tel = tel
}

init(snapShot: FIRDataSnapshot){
self.name = (snapShot.value! as! NSDictionary)["name"] as! String
self.age = (snapShot.value! as! NSDictionary)["age"] as! String
self.gender = (snapShot.value! as! NSDictionary)["gender"] as! String
self.description = (snapShot.value! as! NSDictionary)["description"] as! String
self.hair = (snapShot.value! as! NSDictionary)["hair"] as! String
self.skin = (snapShot.value! as! NSDictionary)["skin"] as! String
self.tel = (snapShot.value! as! NSDictionary)["tel"] as! String

}

func toAnyObject() -> [String: Any]{
return ["name": name, "age": age, "gender": gender, "description": description, "hair": hair, "skin": skin, "tel": tel]
}
}

这是我的获取代码:

ref.child("users").observe(.childAdded, with: { (snapshot) in
if(snapshot.value is NSNull){

}else{
let user = User(snapShot: snapshot)
print("snapshot not nil: \(snapshot.key) \(snapshot.value)")
print("user: \(user.name)")
}

它会有一些数据是空的,比如皮肤和描述,看到了吗?我有一些使用较少键的寄存器,在 android 中这没问题,但在 swift 上它无法处理 nil

第一个寄存器工作正常,但第二个崩溃 My data base

fatal error: unexpectedly found nil while unwrapping an Optional value 2016-12-21 14:13:46.765206 GPMap[6033:1579494] fatal error: unexpectedly found nil while unwrapping an Optional value

最佳答案

将您的函数更改为如下所示以检查值是否存在:

init(snapShot: FIRDataSnapshot){

self.name = (snapshot.value as? NSDictionary)?["name"] as? String ?? ""

// ... continue for other values

}

然后,您不需要检查值是否为 Null(因此没有错误):

ref.child("users").observe(.childAdded, with: { (snapshot) in

let user = User(snapShot: snapshot)

// use the method from User to parse the data
let userData = user.toAnyObject()
print(userData) //Dictionary of data variables

print("snapshot not nil: \(snapshot.key) \(snapshot.value)")
print("user: \(user.name)")

})

关于ios - 使用 Firebase ios 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41325008/

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