Following and Unfollowing
Instagram Firebase
This lesson will cover the aspects of following and unfollowing users in the system. More specifically, we'll make a server call to Firebase Database that will create a branch for following users. Using this branch as our setup, we'll be able to figure out later how to piece together our home feed with all of the necessary posts. Don't forget, once we follow a user, we'll also need to unfollow them. This will be covered in addition to styling our button based on the follow relationship of our users.

Comments (24)
kaevin
6 years ago
Amazing Video! Can you tell me the difference in checking whether the user is following by doing "observeSingleEvent" or to check via "hasChild"?
Brian Voong
6 years ago
johnrm9
6 years ago
Since we want to know the current user uid often maybe this extension would be handy, eg. as in guard let uid = FIRAuth.currentUid else { return } extension FIRAuth { static var currentUid: String? { return FIRAuth.auth()?.currentUser?.uid } }
Brian Voong
6 years ago
Tokyojogo
5 years ago
Hi Brian, can you make a last video introducing all these things? Would really appreciate that.
juliolocoh
6 years ago
HI Brian i know you've been busy but can you do a tutorial about these three cool animations for me i wanna to buy please here are the links check them out https://maniacdev.com/2017/04/glidingcollection-smooth-scrolling-uicollectionview-layout-for-image-based-selections https://maniacdev.com/2017/03/elongation-swift-based-table-view-component-featuring-animations-and-parallax-images https://maniacdev.com/2017/03/request-permission-elegant-swift-based-ui-component-for-handling-app-permissions
juliolocoh
6 years ago
https://maniacdev.com/2017/03/crpageviewcontroller-ios-ui-component-for-customizable-page-view-controllers
Fred van Rijswijk
6 years ago
There all open source and code is on GitHub...
juliolocoh
6 years ago
i want it without storyboard
Hen Shabat
6 years ago
Hi Brian, Is that correct to create "followers" node in Firebase DB and to use the same logic as "following"? In following you use "from" and "to" so it's just should be the opposite( from = to and to = from ), right? Thanks!
Brian Voong
6 years ago
DanApp
6 years ago
Hi Brian, Huge fan of your teachings! I’m currently doing research - on Google of course - for a best practice User Blocking solution for a Firebase project I’m working on. This follow/unfollow lesson looks similar in nature but I’m sure they are completely disparate. Could you share with us your experience implementing a User Blocking strategy using iOS and Firebase? If you could also recommend any online resources on this topic that would be terrific too! Best regards
omari
6 years ago
Hey Brian, if you try to follow an user that has a private account you first have to make a request. I don't have any idea how to implement that feature. Please give us some hints.
omari
6 years ago
Hey Brian There is a huge problem. If you open your own userProfile you can follow and unfollow your self. How can we solve this issue. It would be nice if the edit profile button would work just to see for example how to change the user profile picture or the username. This is very important thanks for your help
victor
6 years ago
Hei Brian I noticed the same problem with Omari. I guess we'll need to implement a different method to fire when the editProfileFollowButton.titleLabel.text == "Edit Profile". For now, I'm simply disabling the button with: if currentLoggedInUserId == userId { editProfileFollowButton.setTitle("Edit Profile", for: .normal) editProfileFollowButton.isEnabled = false }
omari
6 years ago
Hello Brian, There is another issue. If you search a user and open it the text of the editButton shows Edit Profile instead of Follow or unfollow for at least one second. This isn't a good user experience. Is there anyway to avoid that. Shall we use different buttons or how can we solve that ?
Brian Voong
6 years ago
omari
6 years ago
Hey Brian, First of all i set the title of the editProfileFollowButton to "Loading". So that you don't see the Edit Profile title when opening a userprofile that is not yours. Secondly to guarantee that you can't follow and unfollow yourself so that your button only has the title "Edit Profile" you have to change the handleEditProfileOrFollowButton() method. Wrap the code inside it with the following if statement if currentLoggedInUser != userId { ....} and then create an else part to execute code that belongs to edit Profile. func handleEditProfileOrFollowButton(){ print("Execute Edit profile / follow/ Unfollow logic") guard let currentLoggedInUser = FIRAuth.auth()?.currentUser?.uid else { return } guard let userId = user?.uid else { return } if currentLoggedInUser != userId { if editProfileFollowButton.titleLabel?.text == "Unfollow" { FIRDatabase.database().reference().child("following").child(currentLoggedInUser).child(userId).removeValue(completionBlock: { (err, ref) in if let err = err { print("Failed to unfollow user", err) return } print("Succesfully unfollowd user", self.user?.username ?? "") self.setupFollowStyle() }) }else { // Follow logic let ref = FIRDatabase.database().reference().child("following").child(currentLoggedInUser) let values = [userId: 1] ref.updateChildValues(values) { (err, ref) in if let err = err { print("Failed to follow user ", err) return } print("Succesfully followed user", self.user?.username ?? "") self.setupUnfollowStyle() } } } else { print("HandlEditProfile ") } }
omari
6 years ago
Hey Brian, If we don't have an stable internet connection we have a problem. I checked it in Instagram and they put a refresh button inside of the collectionview with the label no internet connection at the bottom. How can you do that ? Also it would be nice while loading the user information to use some kind of progress bar. When the user data is loaded we replace the progress bar with the settings button on the right of the navBar.
Casey West
6 years ago
I did something different here, mostly because of how this page is used in my app. I ended up created brand new view controllers from scratch to handle when you visit someones profile. Is there a reason you wouldn't do this? There is some code repetition, but it does give me a lot of freedom on the visiting profile screen. It also handles the 'Edit profile' button flashing and such. If you would advise against this Brian let me know :)
Brian Voong
6 years ago
Casey West
6 years ago
Yeah I definitely see what you mean. My Utilities folder is growing slowly haha. Thanks for the prompt reply.
esneaker
6 years ago
I did the exact same thing! Glad someone else is of like mind. Good question.
mattnet
6 years ago
Brian, great video...would love to see another tutorial on this, but where the 'following' has to be approved by the user getting followed. I assume it could be done by adding status to the following node where requested or approved are the possible statuses and maybe has a followDate and requestToFollowDate as well...then these of course would trigger some sort of user notification where user can accept or ignore follow request...
Antonio Di Francesco
6 years ago
Brian, this is episode 26 and it lasts exactly 26 minutes...I'm sure you did it on purpose! :) What is the hidden message? :)
Fabio Giolito
6 years ago
I went with setting up three separate buttons with their own separate actions. Makes the code easier to read and allows me to swap them without messing up with style and title (which can change in the future and break the code or ux)
esong2288
5 years ago
Idk if you still come on here, but how did you make it work? Did you anchor them all in the same place, split up the follow, unfollow logic to their respective targets, and just use the isHidden property? I can't seem to figure out how to make it work
Fabio Giolito
5 years ago
I got an email notification of your reply.
Fabio Giolito
5 years ago
Oh no!!! I just answered your comment and it only sent the first line… (I got an email notification of your reply) could be because I had an emoji after that sentence… (Testing another line here to see if it works before typing it all again)
Fabio Giolito
5 years ago
Ok, I just checked the code and here's what I did: 1. Made three separate buttons: Follow, Unfollow, Edit profile. Anchored all to the same place (overlap). 2. Made a function `setupEditOrFollowButton()` that is called when the user variable `didSet`. This function checks if the user is me (shows Edit profile button), otherwise fetches the Follow status from Firebase and shows the correct button (Follow / Unfollow). I'm using the isHidden property to show/hide. 3. Follow and Unfollow buttons have targets to `handleFollow()` and `handleUnfollow()` respectively, that will perform the appropriate action on Firebase and change the isHidden status on the buttons to show the appropriate one. Hope this helps!
RayBee
6 years ago
Hi Brian: "[Firebase/Core] [I-COR000019] Clearcut post completed." is missing in the box(?) below the code and I believe this happens because when I downloaded the pods the only pod missing was FirebaseCore. If this is correct, how do I download this pod after the fact? I noticed it was missing early on in Episode 3 and I thought that it might come back to haunt me. Is there a way to download it separately? I'm up to Episode 27 and even though it says I'm following additional users beyond the current user, the app up to this point doesn't show them in the simulator. Please advise. Thanks!
Brian Voong
6 years ago
RayBee
6 years ago
I also am reading an error message that reads: "Failed to fetch ordered posts: Error Domain=com.firebase Code=1 "Permission Denied: UserInfo={NSLocalizedDescription=Permission Denied}"
Burak Ahmet Şentürk
6 years ago
I had same error , There is a tab which name Rules in Firebase Database.You can modify lines like that { "rules": { ".read": true, ".write": true } } Its fix my problem but I don't know this way safe or not.
alpertabak
5 years ago
Hey Burak, I think this rules will work well but it is not a good fix. Because, to do fetch posts and using app, the user must be logged in. Without authentication user shouldn't use the app.
skpyahoo
6 years ago
Hi, I am using Storyboard for Custom Section Header on UserProfileCollection View, also have respective classes for Header,Coleection View Controller. Everything was working fine from the stat to here till the iteration on button happens. I am able to create IbAction for Button but when I ran the code, Interaction on button is not happening(no click event, I already checked the user interaction is enabled}. Please let me know what additional I can try to fix.
digimarktech
5 years ago
For those who are curious, instead of checking if the snapshot.value is equal to 1, you can just use a method of the Datasnapshot called "exists()". It checks if the node is null, which it would be if you are not currently following someone. So essentially you would write if snapshot.exists() { }
Tokyojogo
5 years ago
Hi Brian, great tutorial. I have a question though. I didn't quite understand when you set let values = [userId: 1] Why is this needed and what is this doing? Also, what would happen if you are following someone and that person deletes his account? Is this something that you will tackle later on in this course? Thank you.
Brian Voong
5 years ago
Kenny Ho
5 years ago
Hi community, I finished this up to Ep 41. before Brian came out with new videos. I came back to rewatch these videos because they are so insightful. Just curious, did anyone add in the feature that shows the total number of photos you posted in "posts" or display the count of followers you have?
flashtrend
4 years ago
Hi how are you, did you find a solution to this?
Shehryar Bajwa
4 years ago
Hey Brian, I think we'd benefit if you shared your Firebase rules page with us
flashtrend
4 years ago
Hi Brian, really enjoying the videos. I am trying to get the count of followers and following to display on a users profile page. How would I go about doing that? Appreciate all the help!
Clint Larenz Nurse
4 years ago
Did you completely ignore the edit profile button for current users? When I tap on the button it follows and unfollows myself.
Brian Voong
4 years ago
Clint Larenz Nurse
4 years ago
I see.. also if I download your complete project, will I be able to see the code on where you update the number of followers and following a user has? I see you had it on the preview of the completed project.
Cinquain
4 years ago
That video was lit
diegoseb
3 years ago
Hi Brian, I've seen you usually use guard statements separate from each other instead of grouping them in just one. E.g: This: guard let1... guard let2... Instead of: guard let1, let2... Does this have any advantage in performance or debugging? Or this depends on the programmer's -style-? Thank you
Brian Voong
3 years ago
HELP & SUPPORT