2

I have a follow/unfollow button and am accessing it by "sender". I am changing the text when the user taps it to follow or unfollow another user. Problem is that when it should show "unfollow" it is showing the default text used in storyboard. The button changes to "follow" as it should, but not "unfollow". Also, I have to use "sender: UIButton" because I am accessing the tableview cells "tag" for the right information.

@IBAction func followButton(_ sender: UIButton) {
    //self.yourFollowing.removeAll()
    //self.following.removeAll()
    self.followingTableView.reloadData()

    let accessData = self.yourFollowing[sender.tag].dataPass
    let businessUid = accessData["uid"] as! String
    let businessName = accessData["businessName"] as! String
    let businessStreet = accessData["businessStreet"] as! String
    let businessCity = accessData["businessCity"] as! String
    let businessState = accessData["businessState"] as! String
    let businessZip = accessData["businessZIP"] as! String
    let businessPhone = accessData["businessPhone"] as! String
    let businessLatitude = accessData["businessLatitude"] as! String
    let businessLongitude = accessData["businessLongitude"] as! String
    let businessWebsite = accessData["businessWebsite"] as! String

    let businessFacebook = accessData["facebookURL"] as! String
    let businessFoursquare = accessData["foursquareURL"] as! String
    let businessGoogle = accessData["googleURL"] as! String
    let businessInstagram = accessData["instagramURL"] as! String
    let businessSnapchat = accessData["snapchatURL"] as! String
    let businessTwitter = accessData["twitterURL"] as! String
    let businessYelp = accessData["yelpURL"] as! String


    let userID = Auth.auth().currentUser!.uid
    let ref = Database.database().reference()
    let key = ref.child("Businesses").childByAutoId().key
    var isFollower = false

    let followersRef = "followers/\(businessUid)/\(self.loggedInUserData?["uid"] as! String)"
    let followingRef = "following/" + (self.loggedInUserData?["uid"] as! String) + "/" + (businessUid)


    ref.child("Businesses").child(userID).child("following").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in

        if let following = snapshot.value as? [String : AnyObject] {
            for (item, value) in following {
                if value as! String == businessUid {
                    isFollower = true

                    let followersRef = "followers/\(businessUid)/\(self.loggedInUserData?["uid"] as! String)"
                    let followingRef = "following/" + (self.loggedInUserData?["uid"] as! String) + "/" + (businessUid)

                    let childUpdates = [followingRef:NSNull(),followersRef:NSNull()]
                    self.databaseRef.updateChildValues(childUpdates)

                    ref.child("Businesses").child(userID).child("following/\(item)").removeValue()
                    ref.child("Businesses").child(businessUid).child("followers/\(item)").removeValue()


                    sender.titleLabel?.text = "follow"



                    //self.yourFollowing.removeAll()
                    self.following.removeAll()
                    self.followingTableView.reloadData()
                }
            }
        }

        // Follow
        if !isFollower {

            sender.titleLabel?.text = "unfollow"

            let followersData = ["email":self.loggedInUserData?["email"] as! String, "businessName":self.loggedInUserData?["businessName"] as! String]
            let followingData = ["businessName":businessName, "businessStreet":businessStreet, "businessCity":businessCity, "businessState":businessState, "businessZIP":businessZip, "businessPhone":businessPhone, "businessWebsite":businessWebsite,"businessLatitude":businessLatitude, "businessLongitude":businessLongitude, "facebookURL":businessFacebook, "twitterURL":businessTwitter, "instagramURL":businessInstagram, "googleURL":businessGoogle, "yelpURL":businessYelp, "foursquareURL":businessFoursquare, "snapchatURL":businessSnapchat, "uid":businessUid]


            let childUpdates = [followersRef:followersData, followingRef:followingData]
            self.databaseRef.updateChildValues(childUpdates)

            let following = ["following/\(key)" : businessUid]
            let followers = ["followers/\(key)" : userID]

            ref.child("Businesses").child(userID).updateChildValues(following as Any as! [AnyHashable : Any])
            ref.child("Businesses").child(businessUid).updateChildValues(followers)




            self.yourFollowing.removeAll()
            self.following.removeAll()
            self.followingTableView.reloadData()
        }
    })



}
Lukas Bimba
  • 817
  • 14
  • 35
  • First, it looks like you're doing thing backwards... in your code, you set `isFollower = true` and then set the button title to "follow", and `if !isFollower` (meaning, if isFollower is false) set the title to "unfollow"? Seems like it should be the other way around. Also, you should be using `sender.setTitle("follow", for: .normal)` instead of setting the text of the button's label. – DonMag Sep 27 '18 at 17:58
  • I'd suggest stripping out all extraneous code (you included a few dozen lines of it) and then test. It might expose the actual problem? And sure, if not, post *that* code so we can duplicate things. –  Sep 27 '18 at 18:07

1 Answers1

2

Your problem is this line in your button action

@IBAction func followButton(_ sender: UIButton) {
    .
    .
    var isFollower = false
    .
    .
}

You are declaring the variable isFollow inside the button action. This means that every time regardless of follow or unfollow, your isFollower is false which is why the condition for follow will work. But the change to true which is inside the completion of follow won't reflect next time you click the button because you are resetting isFollower to false.

Solution: Move the variable isFollow outside the button action.

var isFollow = false

@IBAction func followButton(_ sender: UIButton) {
     // Your logic
}

Also your logic inside the completion seems wrong. Something like the code below should be there to change it to false.

if value as! String == businessUid {
    isFollower = !isFollower
    if isFollower {
        // Follow logic
        sender.setTitle("unfollow", for: .normal)
    } else {
        // Unfollowed logic
        sender.setTitle("follow", for: .normal)
    }
    // Reload table
}
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
  • if you have intilized the isFollow that there is no need of specifying type, Swift infers that – Abid Nawaz Sep 27 '18 at 17:49
  • @AbidNawaz Yes. I've made it a habit to have type beside the variable for neatness and clarity. – Rakesha Shastri Sep 27 '18 at 18:00
  • I don't think this is correct... the OP *does* declare `var isFollower = false` inside the func, but then if conditions are met the code includes the line `isFollower = true`. So, when code execution gets to the `if !isFollower {` line, it *is* possible that the value has changed. – DonMag Sep 27 '18 at 18:01
  • @DonMag yes, i read it carefully and am still trying to understand what his code does. He seems to have an API call which he will treat as follow if it is a success. So, does that mean for unfollowing, there doesn't need to be any API call? Or is he supposed to invert the `isFollower` inside the API call. If so, why is his unfollow logic outside? – Rakesha Shastri Sep 27 '18 at 18:03
  • @LukasBimba what is that API call for? Updating follow unfollow status? – Rakesha Shastri Sep 27 '18 at 18:04
  • yes, they both have calls to update or remove Childs depending on if the user is following or unfollowing the other user. – Lukas Bimba Sep 27 '18 at 18:05
  • @LukasBimba there seems to be some logic problem in your API completion. – Rakesha Shastri Sep 27 '18 at 18:08
  • @LukasBimba not that one. The current one. – Rakesha Shastri Sep 27 '18 at 18:15
  • @LukasBimba - have you stepped through your code in debug to make sure it's doing what you ***think*** it's doing? – DonMag Sep 27 '18 at 18:16
  • Now the problem is when the view controller loads, it has the default text because the "setTitle" works off of actions – Lukas Bimba Sep 27 '18 at 18:18
  • When I tap the "follow" "Unfollow" button the buttons text changes correctly – Lukas Bimba Sep 27 '18 at 18:19
  • @LukasBimba The best solution would be for the API give your the information about whether it is going to change to follow or unfollow, because, then whatever you do on the web would also need to reflect. If that is not possible, then you might need to use userdefaults to save the state of the button. – Rakesha Shastri Sep 27 '18 at 18:21
  • ill just set the default text to "unfollow" since this is the "following" page and there won't be data unless the user is following people – Lukas Bimba Sep 27 '18 at 18:23
  • Can you try replacing sender.titleLabel?.text to sender.setTitle method ? And give a try ? – Ashish Sep 27 '18 at 18:43