登录时将帖子添加到其他用户的帖子

埃里克·沃尔特斯

我有一个允许用户发帖的应用程序。我注意到当用户创建一个时post,帖子被正确添加到他们的posts. 但是,当该用户注销并且我登录另一个用户时,它post会附加到新登录用户的posts. 因此,两个用户的posts. 我无法弄清楚这是怎么回事。我曾尝试使用断点,但我什至找不到代码可能在哪里执行此操作。添加帖子的代码是:

@IBAction func postButtonTapped(_ sender: Any) {


            guard let beverageNameAdd = beverageName.text, beverageNameAdd != "" else {
                print("ERIC: Caption must be entered")
                return
            }

            if bevCat == "Wine" {
                guard let wineVintageAdd = wineVintage.text, wineVintageAdd != "" else {
                    print("ERIC: Vintage must be entered")
                    return
                }

                self.wineCount = self.wineCount + 1
                db.collection("users").document(uid!).setData([ "wineCount": self.wineCount!], merge: true)
            }

            if bevCat == "Beer" {
                self.beerCount = self.beerCount + 1
                db.collection("users").document(uid!).setData([ "beerCount": self.beerCount!], merge: true)
            }

            if bevCat == "Liquor" {
                self.liquorCount = self.liquorCount + 1
                db.collection("users").document(uid!).setData([ "liquorCount": self.liquorCount!], merge: true)
            }

             guard let beverageTypeAdd = beverageType.text, beverageTypeAdd != "" else {
                print("ERIC: Vintage must be entered")
                return
            }

            guard let img = newPostImage.image, imageSelected == true else {
                print("ERIC: An image must be selected")
                return
            }



            if let imageData = img.jpegData(compressionQuality: 0.2) {

                let imgUid = NSUUID().uuidString
                let metadata = StorageMetadata()
                metadata.contentType = "image/jpeg"
                let storageItem = STORAGE_BASE.child(imgUid)
                print("STORAGE ID: \(storageItem)")


                DataService.ds.REF_POST_IMAGES.child(imgUid).putData(imageData, metadata: metadata) { (metadata, error) in
                    if error != nil {
                        print("ERIC: Unable to upload image to Firebasee torage")
                    } else {
                        print("ERIC: Successfully uploaded image to Firebase storage")
                        DataService.ds.REF_POST_IMAGES.child(imgUid).downloadURL(completion: { (url, error) in
                            if error != nil {
                                print("ERROR in image \(error!)")
                                print("Error URL for image: \(String(describing: url))")
                                return
                            }
                            if url != nil {
                                self.postToFirebase(imgUrl: url!.absoluteString)
                                print("URL for image: \(String(describing: url))")
                            }
                        })
                    }
                }
            }
            performSegue(withIdentifier: "reloadFeed", sender: self)
        }

        func postToFirebase(imgUrl: String) {
            let post: Dictionary<String, AnyObject> = [
                //"postTimeStamp":  [".sv" : "timestamp"] as AnyObject,
                "beverageName": beverageName.text! as AnyObject,
                "imageUrl": imgUrl as AnyObject,
                "beverageType": beverageType.text! as AnyObject,
                "wineVintage": wineVintage.text! as AnyObject,
                "beverageRating": beverageRating.rating as AnyObject,
                "beveragePrice": beveragePrice.text! as AnyObject,
                "beverageCategory": bevCat as AnyObject,
                "uid": uid as AnyObject
            ]


            let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
            firebasePost.setValue(post)
            let userPost = firebasePost.key

            print("Firebase Post: \(String(describing: firebasePost))")

            let followerList = DataService.ds.REF_USERS.child("\(uid!)").child("followers")

            followerList.observe(.value, with: { (snapshot) in

                if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
                    for snap in snapshot {
                        print("SNAP -- \(snap.key)")

                        DataService.ds.REF_TIMELINE.child("\(snap.key)").child("\(userPost!)").setValue(true)
                    }
                }
            })

            print("ADDING POST \(userPost!)")
            _ = Auth.auth().addStateDidChangeListener { (auth,user) in
                if let user = user {
                    let userId = user.uid
                    print("USER: \(String(describing: userId))")
                    let newPost = DataService.ds.REF_USERS.child("\(userId)").child("posts").child(userPost!)
                    newPost.setValue(true)

                }
            }

            beverageName.text = ""
            beverageType.text = ""
            beveragePrice.text = ""
            imageSelected = false
            newPostImage.image = UIImage(named: "icons8-camera-100")

        }

然后,退出的代码在这里:

@IBAction func logoutTapped(_ sender: Any) {
        let firebaseAuth = Auth.auth()
        do {
            try firebaseAuth.signOut()
            let _: Bool = KeychainWrapper.standard.removeObject(forKey: KEY_UID)
            performSegue(withIdentifier: "signOut", sender: self)
        }
        catch let signOutError as NSError {
          print ("Error signing out: %@", signOutError)
        }
}

然后登录的代码在这里:

@IBAction func loginPressed(_ sender: UIButton) {
    if let email = emailInput.text, let pwd = passwordInput.text {
        Auth.auth().signIn(withEmail: email, password: pwd) { [weak self] user, error in
            guard self != nil else { return }
            if let user = user {
                let uid = user.user.uid
                let userData = ["provider": user.user.providerID]
                self!.completeSignIn(id: uid, userData: userData)
            } else {
                let alert = UIAlertController(title: "Email/Password Incorrect", message: "The username/password combination is incorrect. Try again.", preferredStyle: UIAlertController.Style.alert)
                alert.addAction(UIAlertAction(title: "Okay", style: UIAlertAction.Style.default, handler: nil))
                self!.present(alert, animated: true, completion: nil)
            }
        }
    }
}

我知道诊断此问题可能需要更多条件,但在我看来,基于 Firebase 实时数据库,旧用户的帖子会在新用户登录时立即附加。有没有人以前见过这种行为或知道如何我可以开始调试这个吗?

埃里克·沃尔特斯

正如@Jay 所指出的,这个问题与

    _ = Auth.auth().addStateDidChangeListener { (auth,user) in
        if let user = user {
            let userId = user.uid
            print("USER: \(String(describing: userId))")
            let newPost = DataService.ds.REF_USERS.child("\(userId)").child("posts").child(userPost!)
            newPost.setValue(true)

        }
    }

每当身份验证发生变化时,我都会将帖子添加到用户的帖子中,这没有任何意义。我只需要在用户按下添加帖子时添加帖子。我删除了所有这些代码,除了:

let newPost = DataService.ds.REF_USERS.child("\(uid)").child("posts").child(userPost!) newPost.setValue(true)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

热门获取属于其他用户的用户的帖子

如果是您的个人资料,则新闻提要中的帖子会重复出现,其他用户的帖子只会出现一次

用户似乎以其他用户身份登录

在Android中以其他用户身份登录时编辑分析用户信息

Laravel以其他用户身份登录

如何为其他用户添加内容?

在Perforce中,如何将文件添加到其他用户的现有存储架中?

Flutter Firebase将其他用户信息(例如地址)添加到数据库

将Autodesk Forge App转移给其他用户

将Outlook日历转移给其他用户

如何添加其他用户以将快照发布到sonatype?

使用sudo时询问其他用户的密码

将SMB登录从访客更改为其他用户?

使用Google登录时如何与其他用户登录?

尝试由其他用户在/ root /中运行程序,方法是将其添加到path

无法登录Debian系统上的其他用户

当其他用户登录时,如何阻止Debian xfce中的关机或重新启动

以其他用户身份登录Firebase

Facebook4j:从用户获取提要,但不包括其他用户的帖子

Acts_As_Votable无法对其他用户的帖子进行投票

无法将其他用户添加到 Windows 10 1909 的全新安装

如何防止用户编辑或删除其他用户帖子?姜戈

不能设置其他用户账号登录

使用 Laravel 5.5 策略阻止其他用户查看帖子

对登录的其他用户使用 source 命令

当与其他用户登录时,它仍然从任何地方选择以前的用户 uuid

Firebase:用户只能看到他添加到 firebase 的内容。其他人不应看到其他用户的数据。如何?

Django 限制其他用户编辑帖子

当其他用户登录“我的”系统时如何获得通知?