如何允许用户只获取他们自己的数据?迅速

Posted

技术标签:

【中文标题】如何允许用户只获取他们自己的数据?迅速【英文标题】:How do I allow a user to only fetch their own data? Swift 【发布时间】:2021-12-03 02:23:08 【问题描述】:

我已经在我的应用中实现了 Firebase。我可以按下一个按钮并将所需的数据发送到 Firebase。我还设置了一个表格视图,以便将所需的数据添加到表格视图中。但是,当任何用户按下按钮发送数据和更新表时,所有数据都会被拉出,甚至来自其他用户。似乎正在提取整个数据库,而不是特定于用户的数据库。我希望用户能够根据他们的 uid 而不是其他用户的 uid 获得他们输入/保存的干手选项。我认为这与这部分代码有关: let handDryLocations = ["id":key

我对这一切都很陌生,因此非常感谢任何帮助。代码如下:

import UIKit
import Firebase
import FirebaseDatabase

class HandDrySaveViewController: UIViewController, UITableViewDelegate, UITableViewDataSource 

    var refHandrylocations: DatabaseReference!
    
    @IBOutlet weak var BestOption: UILabel!
    
    override func viewDidLoad() 
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(didGetNotification4(_:)), name: Notification.Name("text4"), object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(didGetNotification5(_:)), name: Notification.Name("text5"), object: nil)
        
        if FirebaseApp.app() == nil 
            FirebaseApp.configure()
        
        
        refHandrylocations = Database.database().reference().child("users");
        
        refHandrylocations.observe(DataEventType.value, with:(snapshot) in
            if snapshot.childrenCount>0
                self.handDryList.removeAll()
                
                for handDryOptions in snapshot.children.allObjects as![DataSnapshot]
                    let handDryObject = handDryOptions.value as? [String: AnyObject]
                    let handDryLocation = handDryObject?["handrylocation"]
                    let handDryBest = handDryObject?["handdrybest"]
                    let handDryString = handDryObject?["handdryoption"]
                    let handDryId = handDryObject?["id"]
                    
                    let handDry = HandDryModel(id: handDryId as! String?, location: handDryLocation as! String?, best: handDryBest as! String?, options: handDryString as! String?)
                    
                    self.handDryList.append(handDry)
                
                
                self.handDryTable.reloadData()
            
        )
        // Do any additional setup after loading the view.
    
    
    @IBAction func BacktoHDCalcButton(_ sender: UIButton) 
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(identifier: "TowelVDryer")
        vc.modalPresentationStyle = .overFullScreen
        present(vc, animated: true)
    
    
    func addHandDryLocation()
        let key = refHandrylocations.childByAutoId().key
        
        let handDryLocations = ["id":key,
                                "handrylocation": HandDryLocation.text! as String,
                                "handdrybest" : BestOption.text! as String,
                                "handdryoption" : HandDryOptionsString.text! as String
                                    ]
        refHandrylocations.child(key!).setValue(handDryLocations)
        
        OptionSavedMessage.text = "Location Saved"        
        
    
    @IBOutlet weak var HandDryOptionsString: UILabel!
    @IBOutlet weak var HandDryLocation: UITextField!
    
    @IBOutlet weak var OptionSavedMessage: UILabel!
    @IBAction func BackButton(_ sender: UIButton) 
    
    
    
    @objc func didGetNotification4(_ notification: Notification)
        let text = notification.object as! String?
        HandDryOptionsString.text = text
    
    
    @objc func didGetNotification5(_ notification: Notification)
        let text = notification.object as! String?
        BestOption.text = text
    
    
    @IBAction func SaveHandDryButton(_ sender: UIButton) 
        addHandDryLocation()
    
    
    @IBOutlet weak var handDryTable: UITableView!
    
    var handDryList = [HandDryModel]()
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
        return handDryList.count
    
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HandDrySavedTableViewCell
        
        let handDry: HandDryModel
        
        handDry = handDryList[indexPath.row]
        
        cell.locationOfOption.text = handDry.location
        cell.bestOption.text = handDry.best
        cell.optionString.text = handDry.options
        
        return cell
    

【问题讨论】:

谢谢。感谢您的帮助,但说实话,我不知道该怎么做。我尝试用您所说的内容替换您指出的两行代码并将“id”:key更改为“uid”:key,但这没有用。你介意再带我看看吗? 【参考方案1】:

您正在这里读取所有用户的数据:

refHandrylocations = Database.database().reference().child("users");

refHandrylocations.observe(DataEventType.value, with:(snapshot) in

如果您只想读取特定用户的数据,则必须更改此代码以指定要读取数据的用户。


例如,如果您使用每个用户的 UID 作为密钥存储了每个用户的信息,那么您可以通过以下方式仅读取该密钥:

refHandrylocations = Database.database().reference().child("users");
var uid = Auth.auth().currentUser!.uid; // See https://firebase.google.com/docs/auth/ios/manage-users#get_the_currently_signed-in_user

refHandrylocations.child(uid ).observe(DataEventType.value, with:(snapshot) in
    let handDryObject = snapshot.value as? [String: AnyObject]
    let handDryLocation = snapshot?["handrylocation"]
    let handDryBest = snapshot?["handdrybest"]
    let handDryString = snapshot?["handdryoption"]
    let handDryId = snapshot?["id"]
    ...

【讨论】:

【参考方案2】:

这就是我最终要做的。我敢肯定它对专业人士来说并不完美,但它可以为我完成工作。

guard let user = Auth.auth().currentUser?.uid else  return 

ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quotes").childByAutoId().setValue(quotesLabel.text!)

【讨论】:

以上是关于如何允许用户只获取他们自己的数据?迅速的主要内容,如果未能解决你的问题,请参考以下文章

DB Design 允许用户定义产品、产品规格并让他们自己插入订单

如何允许用户在我的 MVC 网站上创建自己的子域? [复制]

Firebase 的“规则不是过滤器”约束的解决方法

使用 JWT 和路由的 Express REST API

如何允许用户在 Spring Boot / Spring Security 中仅访问自己的数据?

基于用户过滤数据库检索