我试图访问存储在Firebase仪表板中的值,以在类中的不同函数和方法中使用它们。
I used this method in this question
我试图打印它们的值,整个应用程序崩溃了,这给了我他们零!
他们实际上不是零!
我在viewDidLoad中使用了类似的方法,并且可以将值检索到标签!
let refer = FIRDatabase.database().reference().child("UserDevices")
var globalEmail : String!
var globalPhone : String!
var globalImageUrl: String!
override func viewWillAppear(_ animated : Bool){
super.viewWillAppear(animated)
retrieveUserData{(email,phone,ImageUrl) in
self.globalEmail = email
self.globalPhone = phone
self.globalImageUrl = ImageUrl
}
}
func retrieveUserData(_ completionBlock : @escaping ((_ email : String?, _ phone : String?, _ ImageUrl: String?)->Void)){
refer.child(byAppendingPath: self.strUserid as String).observe(.value , with: {snapshot in
if let userDict = snapshot.value as? [String:AnyObject] {
completionBlock(userDict["email"] as! String, userDict["phone"] as! String, userDict["ImageUrl"] as! String)
}
})
}
var strUserid : NSString!
override func viewDidLoad() {
super.viewDidLoad()
print(globalEmail)
print(globalImageUrl)
print(globalPhone)
self.navigationController?.navigationBar.tintColor = UIColor.white
print("idis \(self.strUserid)")
let ref = FIRDatabase.database().reference().child("UserDevices")
self.navigationController?.navigationBar.tintColor = UIColor.white
ref.child(byAppendingPath: self.strUserid as String).observe(.value, with: { snapshot in
if let dict = snapshot.value as? NSMutableDictionary{
print("dict is \(dict)")
if let Provider = dict["name"] as? String
{
self.DeviceDetailsProvider.text = Provider
// self.navigationItem.title = Provider
}
if let name = dict["DeviceName"] as? String
{
self.DeviceDetailsName.text = name
self.navigationItem.title = name
}
if let ShortDescription = dict["Description"] as? String
{
self.DeviceDetailsDescription.text = ShortDescription
}
if let City = dict["city"] as? String
{
self.DeviceDetailsCity.text = City
}
}
})
self.DeviceDetailsImageView.downloadedFrom(link: globalImageUrl)
}
为什么我在这里撞车!
最佳答案
更改ref.child(byAppendingPath: self.strUserid as String)
至:-
ref.child(self.strUserid)
同时删除
let refer = FIRDatabase.database().reference().child("UserDevices")
。您无法在范围外全局初始化您的引用,因为您不知道类的初始化顺序,并且可能的情况是,当您尝试初始化
let refer
时,甚至还没有初始化FIRDatabase。代替在
refer
中使用retrieveUserData
FIRDatabase.database().reference().child("UserDevices")
您可以在viewController的LIFE CYCLE中看到,viewdidLoad在viewWillAppear之前被调用:
因此,您需要的是:-
override func viewDidLoad() {
super.viewDidLoad()
..
retrieveUserData{(email,phone,ImageUrl) in
self.globalEmail = email
self.globalPhone = phone
self.globalImageUrl = ImageUrl
self.DeviceDetailsImageView.downloadedFrom(link: globalImageUrl)
// .. Do your stuff...
}
}
读取:Viewcontroller's Lifecycle