Apologies
You must be signed in to watch this lesson.
Manual Automatic Post Refresh
Instagram Firebase
In today's lesson, we're going to cover the topic of implementing an easy way to refresh our feed using a UIRefreshControl. This component allows us to present a UIActivityIndicatorView when we drag our UICollectionView down to refresh. Next, we'll look at how to automatically refresh our home feed every time we upload a new post to Firebase Database. For this to work, we'll look at implementing NotificationCenter observers.

Comments (32)
Nathan Hsiao
6 years ago
Hi Brian, instead of notification center to automatically update my feed, is to use firebase observe child added. Is it a better way of automatically update my feed?
Brian Voong
6 years ago
victor
6 years ago
hey Brian I guess we can also use notificationCenter to update Feed everytime Follow / UnFollow changes?
Brian Voong
6 years ago
victor
6 years ago
Oops. totally forgot about the UX. lesson for me thanks, Sifu :)
albaqawi
6 years ago
Hi Brain is there a solution to this Firebase async refresh posts fetch? I tried everything from disabling viewControllers to other ideas but no luck. I get the same error that indexPath out of rage o cell.post. Strange enough even when I refresh on device without changing any followers list. please help
Te-Jen Wu
6 years ago
Hi Brian, I found if dragging the refresh control several times, the app will crash, and there is a fatal error: "Index out of range" showed. Can you please tell us how to fix the problem?
Hen Shabat
6 years ago
I solved that issue at CellForRow ( HomeController ) if posts.count > 0 { cell.post = posts[indexPath.item] } I added this if statement to check the posts array.
Nathan Hsiao
6 years ago
i guess its because of removeall but i kinda see other bug that if one of the followed user post earlier than your post it kinda flicker between ur post and his when i refresh
Te-Jen Wu
6 years ago
Thanks for your good advice. Another solution for reference: Don't execute the posts.removeAll so early. I move it to the closure in the FIRDatabase.fetchUserWithUID.
egante
6 years ago
I had the same problem, your solution worked for me, thank you!
victor
6 years ago
Nice fix! :)
cjackmonster
6 years ago
Thank's bro, my update problem fixed :)
nicsgodlike@gmail.com
6 years ago
Thanks Hen
abreyXo
3 years ago
Thanks a million, your solution worked! :)
Hen Shabat
6 years ago
Hi Brian, Do you recommend to use ViewWillAper and call handleRefresh? That's can do refreshing automatically after you back to the home screen and follow / unFollow user. Thanks!
Brian Voong
6 years ago
faraz
6 years ago
Hi Brian, can you show us how to integrate the game of chats app into the Instagram Firebase so we'll have messaging in the app?
Fred van Rijswijk
6 years ago
That's really easy, you have the users already and the code so you can copy that code into this app and bind it to a button for make a new chat or to a tabbar item...
faraz
6 years ago
I tried that, but the complier gives about 20 errors that I don't know how to deal with.
Fred van Rijswijk
6 years ago
//message let messageNavController = templateNavController(unselectedImage: #imageLiteral(resourceName: "chat_line"), selectedImage: #imageLiteral(resourceName: "chat_full"), rootViewController: MessagesController(style: .plain)) Where the MessageController is the same Controller as in the Chat App
faraz
6 years ago
The problem is not in the navcontroller, its with the other parts of the app, since there's a lot code duplication etc.
Brian Voong
6 years ago
faraz
6 years ago
Hey Fred, did u manage to integrate the messages app with the instagram app? If so can I please have the source code?
Fred van Rijswijk
6 years ago
I think the most off us wants to know how to deal with 10000 of posts you don't want to load that in your home feed as a value, but some kind of pagination or something like that
Brian Voong
6 years ago
GeminixClown
6 years ago
Yessss, glad to hear that Brian.... because no one in the internet teaching about pagination on the Firebase.... Glad you will make our dream come true
Hen Shabat
6 years ago
Yes! Follow!
Victor Alisson
6 years ago
Hi, Brian. When do you plan on talking about cloud functions using firebase?
Brian Voong
6 years ago
Hen Shabat
6 years ago
Hi Brian, Can you help with press on the profile image view in every cell at HomeController? DidSelectItemAt Dosent work Because I added tapGesture. Thanks!
Brian Voong
6 years ago
Hen Shabat
6 years ago
I fixed that issue. Thanks!
Qian Kefei
6 years ago
Hi Brian, How do we know when to stop the refreshControl animation? Now it keeps spinning when I drag down the collectionView. The firebase process is a loop with async tasks so that its hard to know when the whole fetch data from database process is finished and call refreshControl.endRefreshing.
Qian Kefei
6 years ago
I try to define a counter to count the totalPost we fetched and after the counter hits the totalPost amount, we stop the animation.
Brian Voong
6 years ago
Qian Kefei
6 years ago
Timer is great, I will try that! Thx!
omari
6 years ago
Hey Brian, Currently we are removing all posts and then filling the array again when refreshing the collectionview. Is this a good approach ??? What happens if we have to load 100 posts or more. Do we have to remove all posts and then add the new ones ? Secondly we have to put this line of code in the cellForItem at method if !self.refreshControl.isRefreshing {} Because the index was empty for a period, the app was occasionally throwing index out of range. It didn't happen every time. I solved it by asking if the refreshControl was finished with refreshing.
omari
6 years ago
Hello Brian, if we don't have any internet connection and try to refresh the homefeed it keeps spinning. Do we have to use a timer that tries to execute the refresh method for e.g. 20 seconds and stops refreshing or is it possible to check wether the internet connection is available and then start refreshing ?
Brian Voong
6 years ago
Amor Lisic
6 years ago
there is one bug in here... if you pull refresh while the app is not fully loaded yet or you pull again while it is refreshing the app crashes
esneaker
6 years ago
I'm having this issue as well. I'm going to keep trying to hammer out why, but if you beat me to it...please share. Thanks!
Morris Liao
6 years ago
Same here. Mine refers back to the cell.post = posts[indexPath.item]. Anyone know how to fix it?
Amor Lisic
6 years ago
I think this happens because of the following the problem is due to the asynchronous nature of the FIREBASE fetch functions combined with the posts.removeAll() call... if we pull refresh multiple times, we perform the removeAll call as well multiple times and somehow screw up the self.posts.append call within the fetch block
Brian Voong
6 years ago
shender ramos
6 years ago
Brian i tried disabling the collection view while refreshing but still wont work... i notice if in collection view number of items in sections in you return posts.count-1 wont crash but you missing one post...i've tried different method but still wont get it to work properly
shender ramos
6 years ago
i found a solution... i dont know if is the right one but its working as right now for me.. self.posts.removeAll() self.fetchAllPost() DispatchQueue.global(qos: .background).async { self.collectionView?.reloadData() self.collectionView?.refreshControl?.endRefreshing() }
faisalmlalani
6 years ago
You shouldn't reload the collection view on the background thread.
Игорь Магурян
6 years ago
very nice car:)
Clive Wong Toh Soon
6 years ago
Hi Brian, I also notice the app crashes whenever you switch from user profile back to HomePage and refresh it quickly. It seems that loading data asynchronously from Firebase causes the post array in different view controllers to confuse and hence run out of index range. Do you have any good fix for that?
omair_34
6 years ago
Hey Brian, if you refresh the HomePage without uploading any post the app crash (index Out of range problem)
Tokyojogo
6 years ago
any fix for this Brian?
diehard98
6 years ago
Hi, Brian When I call function from one class to another class, I though using delegation with protocol is good way of doing it. But you were using NotificationCenter to broadcast custom message through app. Is that better for some reasons I guess? Is NotificationCenter going to handle pop-up messages when new posts are added? (like notification messages for apps). Thanks,
Brian Voong
6 years ago
diehard98
6 years ago
Very quick response! :) Thank you. I see. I thought NotificationCenter is related to some notifications that I usually see on my other apps when they have new messages or posts. Do you have any course that handles notification when new messages or posts are added into Firebase?
Brian Voong
6 years ago
diehard98
6 years ago
Sounds great. Thank you very much! Feels like gift for Thanksgiving. :)
Laurent Maquet
6 years ago
Hey Brian, Finally found a fix for the bug notified by Amor ?
Laurent Maquet
6 years ago
I tried to reload data between clearing posts array and calling fetchAllPosts(), and for some reason, it seems to work now... But unfortunately, I can't really explain it.... @objc func handleRefresh() { posts.removeAll() collectionView?.reloadData() fetchAllPosts() }
Brian Voong
6 years ago
PatrickVB
6 years ago
Thank You!
Maxnelson997
6 years ago
love GTI's. Manual is great too, if not manual, hopefully u got that dual clutch transmission!
Sanket Ray
6 years ago
Hey brian, I found a serious bug...Refresh control works fine...But, if i refresh continuously for 3-4 times, my app crashes with error message "Index out of range".
Brian Voong
6 years ago
Sanket Ray
6 years ago
Is the addressed in the later videos?
Brian Voong
6 years ago
Yusuf Çınar
6 years ago
self.posts.removeAll(keepingCapacity: false)
ansonngch
5 years ago
Finally found the solution :) Thanks Brian!
lsamaria
5 years ago
what is the solution?
Pavol Poláček
6 years ago
Hey Brian. I found that when I added post (via "Share" button) the list of posts is updated correctly and I can see the list updated. However, the update does not work for grid and list views in "UserProfileController". Do you have any trick or recommendation? Thanks Pavol
Maximilian Osborne
6 years ago
Hey Brian, Really enjoying this course! I seem to have a bug that I haven't seen discussed in any of the previous video forums, I have already compared my code with yours multiple times (via download project) and nothing stands out. I wonder if you could give an indication of what may be the problem. So when I navigate between from the User Profile tab to the Home Tab, upon scrolling down my the collection view in the home tab the collection view spontaneously changes it's layout, such to replicate the UserProfile Controller. It does not do this elegantly. It looks chaotic. Weirdly this does not happen when I navigate from another user's page i.e. through the search tab. Could you please pin point why this could be happening and how I could stop this? Thank you!
Brian Voong
6 years ago
Maximilian Osborne
6 years ago
Great This works. Thank you! in MainTabController I made two separate instances as follows: func setupViewControllers() { let layout1 = UICollectionViewFlowLayout() let layout2 = UICollectionViewFlowLayout() let homeNavController = templateNavController(unselectedImage: #imageLiteral(resourceName: "home_unselected"), selectedImage: #imageLiteral(resourceName: "home_selected"), rootViewController: HomeController(collectionViewLayout: layout1)) ..... let userProfileController = UserProfileController(collectionViewLayout: layout2) .... }
meetrobel
5 years ago
Hey Brian, I had a quick question do you refactor your code at some point to implement design patterns such as a facade class to hide away the low level code of fetching information for example? I was just curious because I just took a software architecture class and I am trying to bring everything together hoping to understand how to write good code.
Brian Voong
5 years ago
petar7
5 years ago
Hi brian I have a question , also every time I scroll or execute function handleRefresh my images and images from followed users are being duplicated every time (my profile has 4 pictures and after refreshing 8), what could the fix be ?
Brian Voong
5 years ago
petar7
5 years ago
Never got an answer so quickly , it works! Thank you master
Clint Larenz Nurse
4 years ago
Do you mind posting an example?
Clint Larenz Nurse
4 years ago
Can you show me how to do this please?
azhar
5 years ago
There's a bug where if you drag to far down to refresh the app crashes with an indexPath out of bounds error in the HomeController cellForItem method. Please help!
azhar
5 years ago
Never mind, found the thread for this
Topp Tikapichart
5 years ago
I got the same problem. How do you fix it?
Topp Tikapichart
5 years ago
Already solved it.
Danielvgftv
5 years ago
BY Brian Voong: if indexPath.item < posts.count { cell.post = posts[indexPath.item] }
anantangad
5 years ago
Hello Brian, In the userProfile page in the application, the constraints we provided using the anchor method makes a perfect image for iPhone 7, but when I switched to iPhone X or XR, I get weird images.
Brian Voong
5 years ago
Bùi Xuân Huy
5 years ago
Hi brian I have a question, why didn't you use observe.childAdded in HomeController so that when we add a new Image it will refresh automaticly ?
Bùi Xuân Huy
5 years ago
Nevermind, I understand it.
thenny chhorn
5 years ago
Hello Brian, I followed everything in this video but every time when I scroll to refresh there always post duplications occur, can you tell if there is any way to fix this bug? thanks
Clint Larenz Nurse
4 years ago
Where you able to ever figure it out?
malrhex
4 years ago
Hi there, I am facing an issue when I have followed the user, so I want to search for it and then unfollow it, I make the move, then when I just jump from clicking the unfollow straight to the homeFeed and refresh it crashes.
malrhex
4 years ago
Thread 1: Fatal error: Index out of range on the cell from homeViewController: cell.post = posts[indexPath.item]
jinuman
4 years ago
Hi Brian. Is it alright if I don't remove observer of NotificationCenter? I always put notification observer inside of `viewWillAppear` and remove observer inside of `viewDidDisappear` as far as I know.. Am I right in this logic?
Brian Voong
4 years ago
jinuman
4 years ago
I think I kind of understand. So situation like system running around UITabBarController like Instagram project, I don't have to worry about Notification memory leak unless I have something outside of UITabBarController, right?
Brian Voong
4 years ago
jinuman
4 years ago
OK! Thanks for sincere and quick reply. I really appreciated.
Clint Larenz Nurse
4 years ago
Anyone else having the duplication issue of posts?I forgot to to fix that...old comment section so I do not expect a reply anytime soon..
Clint Larenz Nurse
4 years ago
Temp fix for anyone else who will go through this, make sure you do not click edit profile yet, it ends up following yourself and it will display your uploaded post twice because it acts like you followed another user " Yourself"
MaxApp
4 years ago
Hello Brian, I hope all is good and well! When I downloaded the source code of the project I saw that in the SignUpController you had a piece of code that you have never used so far. // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } I am not really sure what this code is about. Can you please explain it to me. Thank you
Brian Voong
4 years ago
Egya Eshun
4 years ago
Hello Brian and colleagues, is anyone also having a problem of refresh where the app crashes when you follow someone and refreshes your Home Feed by pulling it down? it says "ERROR: INDEX OUT OF RANGE". Please Brian how do i fix this?
sinbad
4 years ago
Same here!
sinbad
4 years ago
Fix: if indexPath.item < post.count { cell.post = post[indexPath.item] }
kor216465
4 years ago
if indexPath.item < posts.count { cell.post = posts[indexPath.item] } post -> posts
Jaylon22
4 years ago
Hey Brian, Awesome tutorial is there a way I could do this for search controller to refresh new users that signed up?
HELP & SUPPORT