我试图在Firebase中获取一个dictionary值,并使用setValuesForKeysWithDictionary方法将其转换为应用程序中的一个“User”类,但它一直失败。如果有人能帮忙解释,我将不胜感激!谢谢
class User : NSObject{
var currentJob : String?
var currentOrg : String?
var hasJobs : Bool?
var hasOrganisations : Bool?
var isCurrentOrgAdmin : Bool?
var organisations : [String : AnyObject]?
}
var user = User()
func bindDataForCurrentUser() -> User {
firebase.child("Users").child(currentUserID).observeEventType(FIRDataEventType.Value) { (snap:FIRDataSnapshot) in
if let dictionary = snap.value as? [String : AnyObject] {
print("dictionary \(dictionary)")
self.user.setValuesForKeysWithDictionary(dictionary)
print("user: \(self.user)")
}
}
return self.user
}
它不会打印到第二行,但这是它在第一行打印的字典:
[“hasorganizations”:1,“isCurrentOrgAdmin”:1,“currentOrg”:-KQFGX4oNcYPjXhlPZ9t,“hasJobs”:0,“organizations”:{
“-KQFGX4oNcYPjXhlPZ9t”=1;“-KQFGZl-M4gSPTEjEXNH”=1;},“当前作业”:-KQKQRfRYF4m3UAMaycd]
提前感谢您的帮助!
编辑:抱歉,忘记添加控制台错误:
字典[“hasorganizations”:1,“isCurrentOrgAdmin”:1,“currentOrg”:-KQFGX4oNcYPjXhlPZ9t,“hasJobs”:0,“organizations”:{“-KQFGX4oNcYPjXhlPZ9t”=1;“-KQFGZl-M4gSPTEjEXNH”=1;},“currentJob”:-KQKQRfRYF4m3UAMaycd]
2016-08-29 13:00:08.909 iComply[49608:5287826]***由于意外异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]:此类不符合密钥hasorganizations的密钥值编码。”
最佳答案
试试这个:-
class User : NSObject{
var currentJob : String?
var currentOrg : String?
var hasJobs : Bool?
var hasOrganisations : Bool?
var isCurrentOrgAdmin : Bool?
var organisations : [String : AnyObject]?
}
var user = User()
func bindDataForCurrentUser() -> User {
let ref = FIRDatabase.database().reference().child("Users")child(FIRAuth.auth()!.currentUser!.uid)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.user = []
if let userDict = snap.value as? [String, AnyObject] {
let specificUser = User()
specificUser.setValuesForKeysWithDictionary(userDict)
self.user.append(specificUser)
}
})
}
return self.user
}
注意:如果要在一个类中插入多个查询,请使用
var user = [User]()
并在observeSingleEventOfType中遍历每个数据捕捉。我之所以在observeEventType上使用observeSingleEventOfType,是因为它在完成后会将观察者从线程中移除。。如果您想继续监听此线程,可以将其改回observeEventType…:)