Listing scheduled notifications in a table view controller - ios

I am trying to list all the notifications a user has created and scheduled in my app, similar to that of the list of alarms in the 'Clock' app from apple. However, each time I get the array of notifications and attempt to display them, they are not being correctly displayed all the time.
Each notification is repeated each day at the same time, so I am using UNUserNotificationCenter.current().getPendingNotificationRequests to get an array of the notifications. With this array of notifications, I iterate over each notification, create a new custom 'Reminder' object and add it to my array of 'Reminders' which I use when I display the notifications in the table view controller.
I do this every time using the viewWillAppear function.
Here is the code:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
generateReminders()
tableView.reloadData()
}
func generateReminders()
{
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { (notifications) in
for item in notifications {
if let trigger = item.trigger as? UNCalendarNotificationTrigger,
let triggerDate = trigger.nextTriggerDate() {
var withSound = true
if(item.content.sound != UNNotificationSound.default)
{
withSound = false
}
self.reminders.append(Reminder(identifier: item.identifier, time: triggerDate, message: item.content.body, withSound: withSound, isAPendingNotification: true))
}
}
self.remindersCount = notifications.count
}
}
When the cells are about to be displayed in the table view controller, I use the 'Reminder' array to customise each cell to display the information of the notification. This is all done in the 'cellForRowAt' function, code below.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Reminder", for: indexPath)
var text = ""
var detailText = ""
if(indexPath.row < remindersCount) {
let reminder = reminders[indexPath.row]
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
text = formatter.string(from: reminder.Time)
detailText = reminder.Message
}
cell.textLabel?.text = text
cell.detailTextLabel?.text = detailText
return cell
}
When a user selects another tab to view, I reset the 'reminders' object to be empty so that when they return to this tab, an updated array of notifications is displayed, code below.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
reminders = [Reminder]()
remindersCount = 0
tableView.setNeedsDisplay()
}
The issue I am facing is this is extremely inconsistent, sometimes all the notifications are displayed, sometimes only some are displayed and other times none of them are displayed. However, each time I print out the count of the number of notifications in the UNUserNotificationCenter.current().getPendingNotificationRequests method it is always the correct number. Furthermore, whenever I click on a cell that should contain information about a notification, the information is there, it is just not being displayed.
Here is a short video of these issues.
https://imgur.com/1RVerZD
I am unsure how to fix this, I have attempted to run the code on the main queue and on the global queue with the quality of service set to '.userInteractive' as shown below, but, still no dice.
let center = UNUserNotificationCenter.current()
let dq = DispatchQueue.global(qos: .userInteractive)
dq.async {
center.getPendingNotificationRequests { (notifications) in
for item in notifications {
if let trigger = item.trigger as? UNCalendarNotificationTrigger,
let triggerDate = trigger.nextTriggerDate() {
var withSound = true
if(item.content.sound != UNNotificationSound.default)
{
withSound = false
}
self.reminders.append(Reminder(identifier: item.identifier, time: triggerDate, message: item.content.body, withSound: withSound, isAPendingNotification: true))
}
}
self.remindersCount = notifications.count
}
}
A small application of this issue occurring can be downloaded from this Github repository.
https://github.com/AlexMarchant98/LitstingNotificationsIssue

There are some issues in your code of tableview as listed below.
You used static cells in your tableview which is not the proper way if you have dynamic rows.
Suggestion : Use Dynamic Prototype Cell for your tableview.
remindersCount not required at all as its already there in your array count.
Suggestion : Use self.reminders.count for array count.
unwindToRemindersTableViewController() method have generateReminders() call which is not required as viewWillAppear() will call when view dismiss.
Suggestion : Check ViewController life cycle you will get proper idea how to reload data.
I have updated some code in your sample project.
Please find updated code here.
Github updated demo
Hope this will helps!

The problem with your code is the timing when tableView.reloadData() gets executed.
UNUserNotificationCenter.current().getPendingNotificationRequests() is a asynchronous call and therefore the reminders array gets filled after tableView.reloadData() was called.
Moving tableView.reloadData() to the end of the callback-block of getPendingNotificationRequests() should fix your issue. (And don't forget to trigger the reloadData() from the main thread)
func generateReminders()
{
let center = UNUserNotificationCenter.current()
let dq = DispatchQueue.global(qos: .userInteractive)
dq.async {
center.getPendingNotificationRequests { (notifications) in
for item in notifications {
if let trigger = item.trigger as? UNCalendarNotificationTrigger,
let triggerDate = trigger.nextTriggerDate() {
var withSound = true
if(item.content.sound != UNNotificationSound.default)
{
withSound = false
}
self.reminders.append(Reminder(identifier: item.identifier, time: triggerDate, message: item.content.body, withSound: withSound, isAPendingNotification: true))
}
}
self.remindersCount = notifications.count
DispatchQueue.main.async {
self.tableView.reloadData() // <---------
}
}
}
}

Related

Trying to reloadData() in viewWillAppear

I have a tabBarController and in one of the tabs I can select whatever document to be in my Favourites tab.
So when I go to the Favourites tab, the favourite documents should appear.
I call the reloading after fetching from CoreData the favourite documents:
override func viewWillAppear(_ animated: Bool) {
languageSelected = UserDefaults().string(forKey: "language")!
self.title = "favourites".localized(lang: languageSelected)
// Sets the search Bar in the navigationBar.
let search = UISearchController(searchResultsController: nil)
search.searchResultsUpdater = self
search.obscuresBackgroundDuringPresentation = false
search.searchBar.placeholder = "searchDocuments".localized(lang: languageSelected)
navigationItem.searchController = search
navigationItem.hidesSearchBarWhenScrolling = false
// Request the documents and reload the tableView.
fetchDocuments()
self.tableView.reloadData()
}
The fetchDocuments() function is as follows:
func fetchDocuments() {
print("fetchDocuments")
// We make the request to the context to get the documents we want.
do {
documentArray = try context.fetchMOs(requestedEntity, sortBy: requestedSortBy, predicate: requestedPredicate)
***print(documentArray) // To test it works ok.***
// Arrange the documentArray per year using the variable documentArrayPerSection.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
for yearSection in IndexSections.sharedInstance.allSections[0].sections {
let documentsFilteredPerYear = documentArray.filter { document -> Bool in
return yearSection == formatter.string(from: document.date!)
}
documentArrayPerSection.append(documentsFilteredPerYear)
}
} catch {
print("Error fetching data from context \(error)")
}
}
From the statement print(documentArray) I see that the function updates the content. However there is no reload of documents in the tableView.
If I close the app and open it again, then it updates.
Don't know what am I doing wrong!!!
The problem is that you're always appending to documentArrayPerSection but never clearing it so I imagine the array was always getting bigger but only the start of the array which the data source of the tableView was requesting was being used. Been there myself a few times.
I assume that reloadData() is called before all data processing is done. To fix this you will have to call completion handler when fetching is done and only then update tableView.
func fetchDocuments(_ completion: #escaping () -> Void) {
do {
// Execute all the usual fetching logic
...
completion()
}
catch { ... }
}
And call it like that:
fetchDocuments() {
self.tableView.reloadData()
}
Good luck :)

How to display tableView only after data fetched from web? (Swift)

I encountered difficulties when loading the Collection views nested in table view cells. The content inside cells would only show after scrolling the table a couple of times. My approach was to use DispatchGroup() in order to fetch the data in a background thread but it didn't work. What is there to do in order to show all the information at once without scrolling through table?
ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
_tableView.isHidden = true
_tableView.dataSource = nil
_tableView.delegate = nil
SVProgressHUD.show()
view.backgroundColor = UIColor.flatBlack()
getData()
dispatchGroup.notify(queue: .main) {
SVProgressHUD.dismiss()
self._tableView.isHidden = false
self._tableView.dataSource = self
self._tableView.delegate = self
self._tableView.reloadData()
}
}
UICollectionView and UITableView datasource / OtherMethods
func getData(){
dispatchGroup.enter()
backend.movieDelegate = self
backend.actorDelegate = self
backend.getMoviePopularList()
backend.getMovieTopRatedList()
backend.getMovieUpcomingList()
backend.getPopularActors()
backend.getMovieNowPlayingList()
dispatchGroup.leave()
}
func transferMovies(data: [String:[MovieModel]]) {
dispatchGroup.enter()
popularMovies = data
dispatchGroup.leave()
}
func transferActors(data: [ActorModel]) {
dispatchGroup.enter()
popularActors = data
dispatchGroup.leave()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "DiscoverCell") as? DiscoverViewCell else { return UITableViewCell()}
cell.categoryLabel.text = cell.categories[indexPath.item]
//categories[indexPath.item]
cell._collectionView.delegate = self
cell._collectionView.dataSource = self
cell._collectionView.tag = indexPath.row
cell._collectionView.reloadData()
self.setUpCell(cell)
return cell
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCell", for: indexPath) as? MovieCollectionViewCell else { return UICollectionViewCell()}
if collectionView.tag == 0{
if let movieDetails = popularMovies["Popular"]?[indexPath.item] {
cell.updateMovieCollectionCell(movie: movieDetails)
}
} else if collectionView.tag == 1{
if let movieDetails = popularMovies["Top rated"]?[indexPath.item] {
cell.updateMovieCollectionCell(movie: movieDetails)
}
} else if collectionView.tag == 2{
if let movieDetails = popularMovies["Upcoming"]?[indexPath.item] {
cell.updateMovieCollectionCell(movie: movieDetails)
} else if collectionView.tag == 3{
cell.movieTitleLabel.text = popularActors?[indexPath.item].name ?? ""
cell.moviePicture.image = popularActors?[indexPath.item].poster
}
} else if collectionView.tag == 4{
if let movieDetails = popularMovies["Now playing"]?[indexPath.item] {
cell.updateMovieCollectionCell(movie: movieDetails)
}
}
return cell
}
MovieCollectionViewCell
class MovieCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var moviePicture: UIImageView!
#IBOutlet weak var movieTitleLabel: UILabel!
func updateMovieCollectionCell(movie: MovieModel){
moviePicture.image = movie.poster
movieTitleLabel.text = movie.name
}
}
DiscoverViewCell
class DiscoverViewCell: UITableViewCell {
#IBOutlet weak var categoryLabel: UILabel!
#IBOutlet weak var _collectionView: UICollectionView!
let categories = ["Popular", "Top Rated", "Upcoming", "Popular People", "Now playing"]
#IBAction func seeMoreAction(_ sender: Any) {
}
}
My intention is to show a loading animation until all the data is fetched and the display the table view cells containing the collection views with fetched data from web.
The desired result should look like this when opening the app
From what I can tell, you're using dispatchGroup incorrectly.
To summarize notify():
it runs the associated block when all currently queued blocks in the group are complete
the block is only run once and then released
if the group's queue is empty, the block is run immediately
The issue I see is that with the way your fetch code is written, the group thinks its queue is empty when you call notify. So the notify() block is run immediately and then you only see the cells populate when they are reloaded during scrolling.
There are two ways to populate a dispatchGroup's queue:
call DispatchQueue.async() and pass the group to directly enqueue a block and associate it with the group
manually call enter() when a block begins and leave() when it ends, which increases/decreases an internal counter on the group
The first way is safer, since you don't have to keep track of the blocks yourself, but the second one is more flexible if you don't have control over what queue a block is run on for example.
Since you're using enter/leave, you need to make sure that you call enter() for each separate work item (in your case, the asynchronous calls to backend), and only call leave() when each one those work items completes. I'm not sure how you're using the delegate methods, but there doesn't seem to one for each backend call, since there are 5 different calls and only 2 delegate methods. It also doesn't look like the delegate methods would be called if an error happened in the backend call.
I would recommend changing the backend calls to use completion blocks instead, but if you want to stick with the delegate pattern, here's how you might do it:
func getData(){
backend.movieDelegate = self
backend.actorDelegate = self
dispatchGroup.enter()
backend.getMoviePopularList()
dispatchGroup.enter()
backend.getMovieTopRatedList()
dispatchGroup.enter()
backend.getMovieUpcomingList()
dispatchGroup.enter()
backend.getPopularActors()
dispatchGroup.enter()
backend.getMovieNowPlayingList()
dispatchGroup.notify(queue: .main) {
SVProgressHUD.dismiss()
self._tableView.isHidden = false
self._tableView.dataSource = self
self._tableView.delegate = self
self._tableView.reloadData()
}
}
func transferPopularMovies(data: [MovieModel]) {
popularMovies = data
dispatchGroup.leave()
}
func transferTopRatedMovies(data: [MovieModel]) {
topRatedMovies = data
dispatchGroup.leave()
}
func transferUpcomingMovies(data: [MovieModel]) {
upcomingMovies = data
dispatchGroup.leave()
}
func transferActors(data: [ActorModel]) {
popularActors = data
dispatchGroup.leave()
}
func transferNowPlayingMovies(data: [MovieModel]) {
nowPlayingMovies = data
dispatchGroup.leave()
}
Don't forget to call the delegate methods even if there is an error to make sure the enter/leave calls are balanced. If you call enter more often than leave, the notify block never runs. If you call leave more often, you crash.
Try this...After getting your data from backend and assigning to moviedetails, set your delegate and datasource to self and reload table.
Set this line into the bottom of getData() function and run
self._tableView.isHidden = false
self._tableView.dataSource = self
self._tableView.delegate = self
self._tableView.reloadData()
and remove from viewdidload()

image and label in interface builder overlap my data in the TableView cell

I am a beginner in iOS development, and I want to make an instagram clone app, and I have a problem when making the news feed of the instagram clone app.
So I am using Firebase to store the image and the database. after posting the image (uploading the data to Firebase), I want to populate the table view using the uploaded data from my firebase.
But when I run the app, the dummy image and label from my storyboard overlaps the downloaded data that I put in the table view. the data that I download will eventually show after I scroll down.
Here is the gif when I run the app:
http://g.recordit.co/iGIybD9Pur.gif
There are 3 users that show in the .gif
username (the dummy from the storyboard)
JokowiRI
MegawatiRI
After asynchronously downloading the image from Firebase (after the loading indicator is dismissed), I expect MegawatiRI will show on the top of the table, but the dummy will show up first, but after I scroll down and back to the top, MegawatiRI will eventually shows up.
I believe that MegawatiRI is successfully downloaded, but I don't know why the dummy image seems overlaping the actual data. I don't want the dummy to show when my app running.
Here is the screenshot of the prototype cell:
And here is the simplified codes of the table view controller:
class NewsFeedTableViewController: UITableViewController {
var currentUser : User!
var media = [Media]()
override func viewDidLoad() {
super.viewDidLoad()
tabBarController?.delegate = self
// to set the dynamic height of table view
tableView.estimatedRowHeight = StoryBoard.mediaCellDefaultHeight
tableView.rowHeight = UITableViewAutomaticDimension
// to erase the separator in the table view
tableView.separatorColor = UIColor.clear
}
override func viewWillAppear(_ animated: Bool) {
// check wheter the user has already logged in or not
Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
RealTimeDatabaseReference.users(uid: user.uid).reference().observeSingleEvent(of: .value, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Any] {
self.currentUser = User(dictionary: userDict)
}
})
} else {
// user not logged in
self.performSegue(withIdentifier: StoryBoard.showWelcomeScreen, sender: nil)
}
}
tableView.reloadData()
fetchMedia()
}
func fetchMedia() {
SVProgressHUD.show()
Media.observeNewMedia { (mediaData) in
if !self.media.contains(mediaData) {
self.media.insert(mediaData, at: 0)
self.tableView.reloadData()
SVProgressHUD.dismiss()
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: StoryBoard.mediaCell, for: indexPath) as! MediaTableViewCell
cell.currentUser = currentUser
cell.media = media[indexPath.section]
// to remove table view highlight style
cell.selectionStyle = .none
return cell
}
}
And here is the simplified code of the table view cell:
class MediaTableViewCell: UITableViewCell {
var currentUser: User!
var media: Media! {
didSet {
if currentUser != nil {
updateUI()
}
}
}
var cache = SAMCache.shared()
func updateUI () {
// check, if the image has already been downloaded and cached then just used the image, otherwise download from firebase storage
self.mediaImageView.image = nil
let cacheKey = "\(self.media.mediaUID))-postImage"
if let image = cache?.object(forKey: cacheKey) as? UIImage {
mediaImageView.image = image
} else {
media.downloadMediaImage { [weak self] (image, error) in
if error != nil {
print(error!)
}
if let image = image {
self?.mediaImageView.image = image
self?.cache?.setObject(image, forKey: cacheKey)
}
}
}
So what makes the dummy image overlaps my downloaded data?
Answer
The dummy images appear because your table view controller starts rendering cells before your current user is properly set on the tableViewController.
Thus, on the first call to cellForRowAtIndexPath, you probably have a nil currentUser in your controller, which gets passed to the cell. Hence the didSet property observer in your cell class does not call updateUI():
didSet {
if currentUser != nil {
updateUI()
}
}
Later, you reload the data and the current user has now been set, so things start to work as expected.
This line from your updateUI() should hide your dummy image. However, updateUI is not always being called as explained above:
self.mediaImageView.image = nil
I don't really see a reason why updateUI needs the current user to be not nil. So you could just eliminate the nil test in your didSet observer, and always call updateUI:
var media: Media! {
didSet {
updateUI()
}
Alternatively, you could rearrange your table view controller to actually wait for the current user to be set before loading the data source. The login-related code in your viewWillAppear has nested completion handers to set the current user. Those are likely executed asynchronously .. so you either have to wait for them to finish or deal with current user being nil.
Auth.auth etc {
// completes asynchronously, setting currentUser
}
// Unless you do something to wait, the rest starts IMMEDIATELY
// currentUser is not set yet
tableView.reloadData()
fetchMedia()
Other Notes
(1) I think it would be good form to reload the cell (using reloadRows) when the image downloads and has been inserted into your shared cache. You can refer to the answers in this question to see how an asynch task initiated from a cell can contact the tableViewController using NotificationCenter or delegation.
(2) I suspect that your image download tasks currently are running in the main thread, which is probably not what you intended. When you fix that, you will need to switch back to the main thread to either update the image (as you are doing now) or reload the row (as I recommend above).
Update your UI in main thread.
if let image = image {
DispatchQueue.main.async {
self?.mediaImageView.image = image
}
self?.cache?.setObject(image, forKey: cacheKey)
}

Swift iOS -How To Reload TableView Outside Of Firebase Observer .childAdded to Filter Out Duplicate Values?

I have a tabBar controller with 2 tabs: tabA which contains ClassA and tabB which contains ClassB. I send data to Firebase Database in tabA/ClassA and I observe the Database in tabB/ClassB where I retrieve it and add it to a tableView. Inside the tableView's cell I show the number of sneakers that are currently inside the database.
I know the difference between .observeSingleEvent( .value) vs .observe( .childAdded). I need live updates because while the data is getting sent in tabA, if I switch to tabB, I want to to see the new data get added to the tableView once tabA/ClassA is finished.
In ClassB I have my observer in viewWillAppear. I put it inside a pullDataFromFirebase() function and every time the view appears the function runs. I also have Notification observer that listens for the data to be sent in tabA/ClassA so that it will update the tableView. The notification event runs pullDataFromFirebase() again
In ClassA, inside the callback of the call to Firebase I have the Notification post to run the pullDataFromFirebase() function in ClassB.
The issue I'm running into is if I'm in tabB while the new data is updating, when it completes, the cell that displays the data has a count and the count is thrown off. I debugged it and the the sneakerModels array that holds the data is sometimes duplicating and triplicating the newly added data.
For example if I am in Class B and there are 2 pairs of sneakers in the database, the pullDataFromFirebase() func will run, and the tableView cell will show "You have 2 pairs of sneakers"
What was happening was if I switched to tabA/ClassA, then added 1 pair of sneakers, while it's updating I switched to tabB/ClassB, the cell would still say "You have 2 pairs of sneakers" but then once it updated the cell would say "You have 5 pairs of sneakers" and 5 cells would appear? If I switched tabs and came back it would correctly show "You have 3 pairs of sneakers" and the correct amount of cells.
That's where the Notification came in. Once I added that if I went through the same process and started with 2 sneakers the cell would say "You have 2 pairs of sneakers", I go to tabA, add another pair, switch back to tabB and still see "You have 2 pairs of sneakers". Once the data was sent the cell would briefly show "You have 5 pairs of sneakers" and show 5 cells, then it would correctly update to "You have 3 pairs of sneakers" and the correct amount of cells (I didn't have to switch tabs).
The Notification seemed to work but there was that brief incorrect moment.
I did some research and the most I could find were some posts that said I need to use a semaphore but apparently from several ppl who left comments below they said semaphores aren't meant to be used asynchronously. I had to update my question to exclude the semaphore reference.
Right now I'm running tableView.reloadData() in the completion handler of pullDataFromFirebase().
How do I reload the tableView outside of the observer once it's finished to prevent the duplicate values?
Model:
class SneakerModel{
var sneakerName:String?
}
tabB/ClassB:
ClassB: UIViewController, UITableViewDataSource, UITableViewDelegate{
var sneakerModels[SneakerModel]
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(pullDataFromFirebase), name: NSNotification.Name(rawValue: "pullFirebaseData"), object: nil)
}
override func viewWillAppear(_ animated: Bool){
super.viewWillAppear(animated)
pullDataFromFirebase()
}
func pullDataFromFirebase(){
sneakerRef?.observe( .childAdded, with: {
(snapshot) in
if let dict = snapshot.value as? [String:Any]{
let sneakerName = dict["sneakerName"] as? String
let sneakerModel = SneakerModel()
sneakerModel.sneakerName = sneakerName
self.sneakerModels.append(sneakerModel)
//firebase runs on main queue
self.tableView.reloadData()
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sneakerModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SneakerCell", for: indexPath) as! SneakerCell
let name = sneakerModels[indePath.row]
//I do something else with the sneakerName and how pairs of each I have
cell.sneakerCount = "You have \(sneakerModels.count) pairs of sneakers"
return cell
}
}
}
tabA/ClassA:
ClassA : UIViewController{
#IBAction fileprivate func postTapped(_ sender: UIButton) {
dict = [String:Any]()
dict.updateValue("Adidas", forKey: "sneakerName")
sneakerRef.?.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
//1. show alert everything was successful
//2. post notification to ClassB to update tableView
NotificationCenter.default.post(name: Notification.Name(rawValue: "pullFirebaseData"), object: nil)
}
}
}
In other parts of my app I use a filterDuplicates method that I added as an extension to an Array to filter out duplicate elements. I got it from filter array duplicates:
extension Array {
func filterDuplicates(_ includeElement: #escaping (_ lhs:Element, _ rhs:Element) -> Bool) -> [Element]{
var results = [Element]()
forEach { (element) in
let existingElements = results.filter {
return includeElement(element, $0)
}
if existingElements.count == 0 {
results.append(element)
}
}
return results
}
}
I couldn't find anything particular on SO to my situation so I used the filterDuplicates method which was very convenient.
In my original code I have a date property that I should've added to the question. Any way I'm adding it here and that date property is what I need to use inside the filterDuplicates method to solve my problem:
Model:
class SneakerModel{
var sneakerName:String?
var dateInSecs: NSNumber?
}
Inside tabA/ClassA there is no need to use the Notification inside the Firebase callback however add the dateInSecs to the dict.
tabA/ClassA:
ClassA : UIViewController{
#IBAction fileprivate func postTapped(_ sender: UIButton) {
//you must add this or whichever date formatter your using
let dateInSecs:NSNumber? = Date().timeIntervalSince1970 as NSNumber?
dict = [String:Any]()
dict.updateValue("Adidas", forKey: "sneakerName")
dict.updateValue(dateInSecs!, forKey: "dateInSecs")//you must add this
sneakerRef.?.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
// 1. show alert everything was successful
// 2. no need to use the Notification so I removed it
}
}
}
And in tabB/ClassB inside the completion handler of the Firebase observer in the pullDataFromFirebase() function I used the filterDuplicates method to filter out the duplicate elements that were showing up.
tabB/ClassB:
func pullDataFromFirebase(){
sneakerRef?.observe( .childAdded, with: {
(snapshot) in
if let dict = snapshot.value as? [String:Any]{
let sneakerName = dict["sneakerName"] as? String
let sneakerModel = SneakerModel()
sneakerModel.sneakerName = sneakerName
self.sneakerModels.append(sneakerModel)
// use the filterDuplicates method here
self.sneakerModels = self.sneakerModels.filterDuplicates{$0.dateInSecs == $1.dateInSecs}
self.tableView.reloadData()
}
})
}
Basically the filterDuplicates method loops through the sneakerModels array comparing each element to the dateInSecs and when it finds them it excludes the copies. I then reinitialize the sneakerModels with the results and everything is well.
Also take note that there isn't any need for the Notification observer inside ClassB's viewDidLoad so I removed it.

UITableView reloadData not working when viewcontroller is loaded a 2nd time

I have a UITableView with custom cell displaying a list of files that can be downloaded. The cell displays the filename and download status. Everything working fine except one scenario :
The user downloads a file and navigates back to the home screen while file download in progress...
He comes back to the previous screen. File download still in progress.
File download complete. I am using tableview.reloadData() at this point to refresh the download status to "Download Complete" but reloadData() not working in this scenario. The cell label still shows "Download in progress".
Scrolling the tableview to get the cell out of screen and back refreshes the cell correctly. Anyway to do this programmatically?"
Otherwise, in normal case where user doesn't change screen, reloadData() is working fine.
Any idea how to fix this?
Thanks
I have used alamofire download with progress in the function below which is inside my UIViewController.
func DownloadFile(fileurl: String, indexPath: NSIndexPath, itemPath: String, itemName: String, itemPos: String, ItemSelected:Bool) {
let cell = myTableView.cellForRowAtIndexPath(indexPath) as! myCustomCell
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, fileurl, destination: destination)
.progress {bytesRead, totalBytesRead, totalBytesExpectedToRead in
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes read on main queue: \(totalBytesRead) / \(totalBytesExpectedToRead)")
let progress = Int((Double(totalBytesRead)/Double(totalBytesExpectedToRead)) * 100)
cell.lblMoreRuqyaFileInfo.text = "Downloading file...(\(progress)%)"
}
}
.response { _, _, _, error in
if let error = error {
print("\(error)")
cell.lblMoreRuqyaFileInfo.text = "Failed to download file. Please try again."
} else {
cell.lblMoreRuqyaFileInfo.text = "File Downloaded sucessfully"
//reloadData() not working from here
self.myTableView.reloadData()
}
}
}
The above func is being called in the tableview's editActionsForRowAtIndexPath below.
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
if myTableView.cellForRowAtIndexPath(indexPath) == nil {
let action = UITableViewRowAction()
return [action]
}
let cell = myTableView.cellForRowAtIndexPath(indexPath) as! myCustomCell
let fileurl = cell.textLabel!.text
let ruqyainfo = cell.lblMoreRuqyaFileInfo.text
let sItemPath = cell.lblCompiledRuqya.text! + "->" + cell.textLabel!.text! + "->\(indexPath.section)->\(indexPath.row)"
let sItemName = cell.lblCompiledRuqya.text!
let sItemPos = "->\(indexPath.section)->\(indexPath.row)"
var bItemSelected:Bool = false
if myTableView.cellForRowAtIndexPath(indexPath)?.accessoryType == UITableViewCellAccessoryType.Checkmark {
bItemSelected = true
} else {
bItemSelected = false
}
//check if file already downloaded,return empty action, else show Download button
if ruqyainfo?.containsString("Download") == false {
let action = UITableViewRowAction()
return [action]
}
let line = AppDelegate.dictCompiledRuqya.mutableArrayValueForKey(AppDelegate.dictCompiledRuqya.allKeys[indexPath.section] as! String)
let name = line[indexPath.row].componentsSeparatedByString("#")
let DownloadAction = UITableViewRowAction(style: .Normal, title: "Download\n(\(name[3]))") { (action: UITableViewRowAction!, indexPath) -> Void in
self.myTableView.editing = false
AppDelegate.arrDownloadInProgressItem.append(name[0])
self.DownloadFile(fileurl!, indexPath: indexPath, itemPath: sItemPath, itemName: sItemName,itemPos: sItemPos, ItemSelected: bItemSelected)
}
DownloadAction.backgroundColor = UIColor.purpleColor()
return [DownloadAction]
}
//Objective C
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.yourTableView reloadData];
}
//Swift
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.yourTableView.reloadData()
}
you can use delegates so that the download controller can tell the first controller that the download is complete, and that it should redraw the tableView - or at least the indexPath that has just completed.
set up the download controller like this
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
let destinationController : DownloadController = segue.destinationViewController as! DownloadController
destinationController.delegate = self
destinationController.indexRowToRefresh = currentlySelectedIndexRow
}
and then in the download completion closure, add something like this
delegate.refreshTableRow(indexRowToRefresh)
and in your first controller, implement the delegate method to refresh this row (or the whole table)
func refreshTableRow(indexRowToRefresh : Int)
{
var indexPath = NSIndexPath(forRow: indexRowToRefresh, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
}
Hey #John Make sure your TableView datasource is reflected with file upload status permanently.I think, when you complete file uploading you change status in tableview datasource
1. First scenario as you are switching to second view controller, and coming back to previous view, it might be reinitializing your datasource. Data source might wasn't permanently reflected.2. In normal scenario, as you are on same view controller(not switching to other). Tableview datasource might be not reinitialized holding updated file upload status.
I suggest to save user file download status saved at some persistant storage or on web server. That doesn't leads to inconsistency in data.
It could be a thread related issue (aka you're coming back from the download thread, not on the UI thread, hence the data is refreshed but not displayed).
Try using this on selfand pass it a selector that refreshes your tableview.
performSelectorOnMainThread:
You used :
let cell = myTableView.cellForRowAtIndexPath(indexPath) as! myCustomCell
and set text for lblMoreRuqyaFileInfo :
cell.lblMoreRuqyaFileInfo.text = "File Downloaded sucessfully"
so, you don't have to call self.myTableView.reloadData()
Try:
dispatch_async(dispatch_get_main_queue()) {
cell.lblMoreRuqyaFileInfo.text = "File Downloaded sucessfully"
}
p/s and where did you call functionDownloadFile , show it, plz!

Resources