Firebaseデータベースからvalues
を取得する最も安全な方法は何ですか?私はnil
をどこにでも持っているので、これを尋ねます。そして、それを追跡することは不可能です。たとえば、私がこのコードを取ったら、どうすればいいのですか?Firebaseから値を取得する最も安全な方法
たとえば、ユーザーが何らかの理由でオフラインでアプリにアクセスした場合、私はnil
を取得してクラッシュします。このよう
、私は、ユーザーを登録してFirebaseデータベースに値を追加します。たとえば、
self.loggedInUser = FIRAuth.auth()?.currentUser
//get the logged in users details
self.databaseRef.child("users").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
//store the logged in users details into the variable
print(self.loggedInUser)
let snapshot = snapshot.value as! [String: AnyObject]
self.usernameLabel.text = snapshot["username"] as! String
if let reputation = snapshot["reputation"] {
self.reputationLabel.text = "\(reputation)"
} else {
print("reputation is nil")
}
if(snapshot["profileImage"] !== nil)
{
let databaseProfilePic = snapshot["profileImage"]
as! String
let data = try? Data(contentsOf: URL(string: databaseProfilePic)!)
self.setProfilePicture(self.profileImageView,imageToSet:UIImage(data:data!)!)
}
self.loadingIndicator.stopAnimating()
}
:
guard let username = usernameField.text, let email = emailField.text, let password = passwordField.text else{
print("Successfully registered")
return
}
if connectedToNetwork() == true{
if passwordField.text == confirmPasswordField.text{
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
if error != nil{
print(error)
return
}
guard let uid = user?.uid else{
return
}
let user = FIRAuth.auth()?.currentUser
user?.sendEmailVerification() { error in
if let error = error {
print(error.localizedDescription)
} else {
print("Email has been sent to you!")
}
}
//Successfully authenticated user
let ref = FIRDatabase.database().reference(fromURL: "https://snuspedia.firebaseio.com/")
let usersReference = ref.child("users").child(uid)
let reputation: Int = 0
let values = ["username": username, "email": email, "reputation": reputation] as [String : Any]// These are the values in Firebase database json tree which I get in next code part.
usersReference.updateChildValues(values, withCompletionBlock: {
(err, ref) in
if err != nil{
print(err)
return
}
print("User saved and logged in")
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main",bundle:nil)
let ProfileViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ProfileViewController")
//Send the user to the LoginViewController
self.present(ProfileViewController, animated: true, completion: nil)
})
})
}else{
let view: MessageView
var config = SwiftMessages.Config()
view = MessageView.viewFromNib(layout: .StatusLine)
view.configureTheme(.error)
config.presentationStyle = .top
config.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
view.configureContent(title: nil, body: "Passwords do not match!", iconImage: nil, iconText: nil, buttonImage: nil, buttonTitle: "Hide", buttonTapHandler: { _ in SwiftMessages.hide() })
SwiftMessages.show(config: config, view: view)
}
}else{
let view: MessageView
var config = SwiftMessages.Config()
view = MessageView.viewFromNib(layout: .StatusLine)
view.configureTheme(.error)
config.presentationStyle = .top
config.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
view.configureContent(title: nil, body: "The internet connection appears to be offline.", iconImage: nil, iconText: nil, buttonImage: nil, buttonTitle: "Hide", buttonTapHandler: { _ in SwiftMessages.hide() })
SwiftMessages.show(config: config, view: view)
}
そして、このように、私は、ユーザーのユーザー名と評判とプロフィール画像を取得しよう最後のコードでは、私がビューに行くたびに、が有効になっていても、persistence
をappDelegate
に設定してもデータを再度ロードします。
私には、すべてprint()
(これは私が知っているデバッグするのは正しくありません)の出力がオプションであるため、すべて間違っているようです。
どうすれば削除できますか?すべてのヒントは高く評価されています。いくつかのエラーを防ぐために、値の一部をuserDefaults
に保存する必要がありますか?または、私はOOPを使用して、ユーザー用の構造体を作成する必要がありますか?
私はそれらについて多くのことを読んだことがありますが、良い答えを見つけることはできません。
あなたのアプリがクラッシュするのは残念だと思っていますが、コード内の特定の場所が無限になっていることを知らずに助けが難しいでしょう。一般的に、[最小限のアプリで問題を再現](http://stackoverflow.com/help/mcve)し、ここでそれを共有すると、最良の結果が得られます。 –
私はnilsを指摘するように頼まなかった。私は選択肢を取り除く方法と、Firebaseからデータを取得する最良の方法を知りたいと思っていました。 –