gpt4 book ai didi

ios - Firebase 获取用户数据 - Swift

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

我想获取数据,我已经多次执行此操作,但由于某种原因它无法正常工作,而且我看不出原因。

我获取数据的代码

func fetchCurrentUserInfo() {

let currentUser = Auth.auth().currentUser!
let currentUserRef = dataBaseRef.child("users").child(currentUser.uid)

currentUserRef.observeSingleEvent(of: .value, with: { (snapshot) in

let user = UserClass(snapshot: snapshot)
self.downloadImageFromFirebase(urlString: user.photoURL!)
self.userName.text = user.getFullName()

//SD Cache
self.userProfileImage.sd_setImage(with: URL(string: user.photoURL!), placeholderImage: UIImage(named: "UserImageTemplate"))

}) { (error) in
let alert = SCLAlertView()
_ = alert.showError("OOPS!", subTitle: error.localizedDescription)
}
}

我的用户类文件

struct UserClass {

var firstName: String?
var email: String?
var photoURL: String?
var uid: String?
var ref: DatabaseReference!
var key: String?
var lastName: String?
var accountType: String?

init(snapshot: DataSnapshot){

key = snapshot.key
ref = snapshot.ref
accountType = (snapshot.value! as! NSDictionary)["Account Type"] as? String
firstName = (snapshot.value! as! NSDictionary)["First Name"] as? String
email = (snapshot.value! as! NSDictionary)["email"] as? String
uid = (snapshot.value! as! NSDictionary)["uid"] as? String
photoURL = (snapshot.value! as! NSDictionary)["photoURL"] as? String
lastName = (snapshot.value! as! NSDictionary)["Last Name"] as? String
}

func getFullName() -> String {
return ("\(firstName!) \(lastName!)")
}

}
}

我已将读写规则设置为 true。当我调用 fetchCurrentUserInfo 函数时,它返回名字、姓氏、 key 等的所有数据,但它返回照片 URL、UID 或电子邮件为 nil 给我错误:fatal error: unexpectedly found nil在展开可选值时

最佳答案

您的崩溃日志说明了一切。您正试图通过 as! 转换强制解包一个可选变量。确保您的快照中有有效值。

另外,更好的模型会喜欢这样,这样更安全:

    struct UserClass {

var firstName: String!
var email: String!
var photoURL: String!
var uid: String!
var ref: DatabaseReference!
var key: String!
var lastName: String!
var accountType: String!

init?(snapshot: DataSnapshot?) {

guard let value = snapshot?.value as? [String: AnyObject],
let accountType = value["Account Type"] as? String,
let firstName = value["First Name"] as? String,
let email = value["email"] as? String,
let uid = value["uid"] as? String,
let photoURL = value["photoURL"] as? String,
let lastName = value["Last Name"] as? String else {
return nil
}

self.key = snapshot?.key
self.ref = snapshot?.ref
self.accountType = accountType
self.firstName = firstName
self.email = email
self.uid = uid
self.photoURL = photoURL
self.lastName = lastName
}

func getFullName() -> String {
return ("\(firstName!) \(lastName!)")
}

}

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

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