Unexpected behaviour of UIRefreshControl during use of UITableView reload data - ios

I'm using UITableView with UIRefreshControl in my UIViewController. When user pulls down the UITableView, UIRefreshControl it works fine. Problem occurs when the data is being fetched. After successful fetching i want UIRefreshControl to stop animate and reload data in the table view.
Video related
The thing is that when I do it as below animation flickers, jumps and god know what else.
private func setupActions() {
mainView.refreshControl.addTarget(self, action: #selector(fetchSurveys), for: .valueChanged)
}
#objc private func fetchSurveys() {
viewModel.fetchSurveys(success: { [weak self] in
self?.mainView.configureEmptyTableView(isHidden: false)
self?.mainView.refreshControl.endRefreshing()
self?.mainView.tableView.reloadData()
}, failure: { [weak self] error in
self?.mainView.configureEmptyTableView(with: "Unable to fetch surveys. Please try again.", isHidden: true)
self?.mainView.refreshControl.endRefreshing()
})
}
I've tried many combinations of order of reloadData() and endRefreshing() and still it doesn't work correctly.

Related

UIRefreshControl is not disappearing after the tableview scrolls to top programmatically

When i want to the update data source of the tableview, firstly i want to scroll to top (to header view) then show the UIRefreshControl view, after data source updated then i want to hide the UIRefreshControll.
To do that i tried following line:
self.kisilerTable.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: false)
self.kisilerTable.setContentOffset(CGPoint(x: 0, y: self.kisilerTable.contentOffset.y - (self.refreshControl.frame.size.height)), animated: true)
self.kisilerTable.refreshControl?.beginRefreshing()
Above code is scrolling to top then it shows the UIRefreshControl. And after my data updated i tried to hide it with following code:
self.kisilerTable.reloadData()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.kisilerTable.refreshControl?.endRefreshing()
}
But the problem is, above code is hiding the indicator animation but it leaves a space there. As you can see in the screenshot:
If i try to hide with following code:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.kisilerTable.reloadData()
self.kisilerTable.refreshControl?.endRefreshing()
}
It is hiding but, i am losing the hide animation. I don't want to lose hide animation.
How can i resolve this problem?
I think it happens, because in the beginning you use setContentOffset to leave a space, but that space is not removed.
I will suggest another implementation, which works very well:
First you declare the refreshControll before the method viewDidLoad():
let refreshControl = UIRefreshControl()
Now do you need create a method for stop the animation when needed:
func stopAnimatingRefreshControl() {
if let refreshControl =
tableView.subviews.first(where: { $0 is UIRefreshControl})as? UIRefreshControl,
refreshControl.isRefreshing {
refreshControl.endRefreshing()
}
}
Now you create an #objc function that be called when scrolls the table to update, normally in this moment you call methods that make your server request to update data.
When this data is updated, you call the function stopAnimatingRefreshControl():
#objc func refreshMyData() {
// call methods for get data from server
getDataFromServer()
}
func getDataFromServer() {
// request completed and data is updated, now i need stop the loading.
DispatchQueue.main.async {
self.tableView.reloadData()
}
stopAnimatingRefreshControl()
}
Finally, after creating the necessary methods, you need to link our #objc function to refreshControll and our tableView, do it in method viewDidLoad() :
refreshControl.addTarget(self, action: #selector(refreshMyData), for: .valueChanged)
tableView.addSubview(refreshControl)
Now you're done, I hope I helped.

UITableViewAlertForLayoutOutsideViewHierarchy error: Warning once only (iOS 13 GM)

I am getting a strange error with iOS13 when performing a Segue and I can't figure out what it means, nor can I find any documentation for this error. The problem is that this seems to cause a lot of lag (a few seconds) until the segue is performed.
2019-09-11 22:45:38.861982+0100 Thrive[2324:414597] [TableView] Warning once only: UITableView was told to layout its visible cells
and other contents without being in the view hierarchy (the table view
or one of its superviews has not been added to a window). This may
cause bugs by forcing views inside the table view to load and perform
layout without accurate information (e.g. table view bounds, trait
collection, layout margins, safe area insets, etc), and will also
cause unnecessary performance overhead due to extra layout passes.
Make a symbolic breakpoint at
UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the
debugger and see what caused this to occur, so you can avoid this
action altogether if possible, or defer it until the table view has
been added to a window. Table view: ; layer = ; contentOffset: {0, 0}; contentSize: {315, 118};
adjustedContentInset: {0, 0, 0, 0}; dataSource: >
I am using Hero but I tried disabling it and using a regular Segue and this hasn't stopped the lag.
The code to initiate the segue is didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
selectedCell = realIndexFor(activeGoalAt: indexPath)
performSegue(withIdentifier: "toGoalDetails", sender: nil)
} else if indexPath.section == 1 {
selectedCell = indexPath.row
performSegue(withIdentifier: "toIdeaDetails", sender: nil)
} else {
selectedDecision = indexPath.row
hero(destination: "DecisionDetails", type: .zoom)
}
}
And then none of the code in viewDidLoad or viewWillAppear from the destination VC affects this in any way (I tried commenting it all out with no difference.
Any idea what's causing this? I can share whatever other details are needed.
Thank you.
It happened to me because I registered the device for change orientation notification in the viewWillAppear(:) method.
I moved the registration in the viewDidAppear(:) and Xcode it's not stopping at the breakpoint anymore.
What I can say is that layout changes might be run when the view is already visible...
For people using DiffableDataSource, set animatingDifferences to false and warning will be gone.
dataSource.apply(snapshot, animatingDifferences: false)
Like #joe-h, I was getting this error and was also surprised as the unwind approach he shows is one used by lots of developers + is in some significant Apple iOS sample code.
The triggering line in my code (#joe-h, I'm guessing likely in yours, too) is a tableView.reloadRows at the selectedIndexPath (which is an unwrapped tableView.indexPathForSelectedRow):
tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
Unfortunately commenting out the row isn't an option if you are unwinding after updating the value in an existing tableView row (which is an approach in the Apple FoodTracker tutorial mentioned above, as well as one used in Apple's Everyone Can Code series). If you don't reload the row(s) then your change won't show in the tableView. After commenting out the reload in the unwind, I added a viewDidAppear with the following code and this seems to fix things:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
}
}
I'd welcome comments on whether this is a sound approach, but for now, this seems to be working.
I had the same error on my Project; A tableView with a diffable datasource. Been bugging on it for hours. Problem lies in updating the snapshot, more specifically on a background thread (default). Forcing the update of the datasource on the main thread got rid of the problem! Hope this helps someone out there!
func updateData(on annotations: [Annotation]) {
var snapshot = NSDiffableDataSourceSnapshot<AnnotationType, Annotation>()
//Append available sections
AnnotationType.allCases.forEach { snapshot.appendSections([$0]) }
//Append annotations to their corresponding sections
annotations.forEach { (annotation) in
snapshot.appendItems([annotation], toSection: annotation.type as AnnotationType)
}
//Force the update on the main thread to silence a warning about tableview not being in the hierarchy!
DispatchQueue.main.async {
self.dataSource.apply(snapshot, animatingDifferences: true)
}
}
This warning can happen du to updating table view or collection view while it is not visible, for example when it is on the parent view controller. To solve that, first, I created a property in the view controller, containing the table view to check if the view controller is visible or not, as bellow:
var isVisible: Bool = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.isVisible = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
self.isVisible = false
}
Then in the data source delegate, before reacting to changes, first check if the view controller is visible. If it was not, do not do any updates. For example
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard isVisible else { return }
tableView.beginUpdates()
}
You should check that visibility before doing any changes in the tableView. For example, in case of NSFetchedResultsController, it must be done in all delegate callbacks which we have implemented.
UPDATE
I recently found that if you update the table view with animation false, even when it is not visible, there won't be any warnings.
I'm new to Xcode/Swift so this may or may not help anyone. I started getting this error after updating to iOS 13 and Xcode 11 within the app when going back to a list from a detail view.
I found that I was doing a tableView.reloadRows and tableView.insertRows in the unwind(as suggested by Apple in one of their tutorials)
#IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
meals[selectedIndexPath.row] = meal
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
// Add a new meal.
let newIndexPath = IndexPath(row: meals.count, section: 0)
meals.append(meal)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
)
I commented out that section of code and it went away.
Oddly enough leaving the sort and self.tableView.reloadData() didn't give me the error.
In viewDidDisappear method I declare tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false) function. Some of you says it's not important but it affected tableView delegate methods. For example viewForHeader function is not called when I get this warning.
I found the most robust and safe way is to wait for the didMoveToWindow of the table view / collection view
as even in viewWillAppear the view may NOT be attached to a window and puting your code in viewDidAppear may cause unwanted graphical glitches
class MyTableViewOrCollectionView: UITableView {
var didMoveToWindowCallback: (()->())? = nil
override func didMoveToWindow() {
super.didMoveToWindow()
didMoveToWindowCallback?()
didMoveToWindowCallback = nil
}
}
and than you can
override func viewDidLoad() {
super.viewDidLoad()
tableView.didMoveToWindowCallback = { [weak self] in
self?.setupInitialContent()
}
}
iPadOS 13.2.3 swift 5.2 Xcode 11.2.1
Just ran into this issue only when starting the app while the device was landscape.
I was calling the detail seque in the viewDidLoad func of the master controller to make sure the detail view was setup correctly.
override func viewDidLoad() {
super.viewDidLoad()
...
self.performSegue(withIdentifier: "showDetail", sender: self)
}
When I removed the performSeque the warning not longer appeared, however,
the left bar buttons on the detail controller no longer worked properly, again only when starting the app while the device was landscape. The left most button would activate the next button to the right instead of what the first button was suppose to do.
The fix for the bar buttons was to add to the viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
...
self.splitViewController?.preferredDisplayMode = UISplitViewController.DisplayMode.allVisible
}
Then execute
override func viewWillAppear(_ animated: Bool) {
self.splitViewController?.preferredDisplayMode = UISplitViewController.DisplayMode.automatic
super.viewWillAppear(animated)
}
I have no explanation why this worked!
This app had worked flawlessly until iPados 13 was loaded.
I am getting similar breakpoint with SwiftUI, without even dealing with viewDidLoad or viewDidappear
//
// ContentView.swift
// DD
//
// Created by Roman Emperor on 3/29/20.
// Copyright © 2020 Emperors. All rights reserved.
//
import Combine
import SwiftUI
// Defining a class Booking of type Bindable Object [changed to ObservableObject]
class Booking: ObservableObject {
var didChange = PassthroughSubject<Void, Never>()
// Array of types to work with
static let types = ["Consultation", "Tooth Pain", "Cleaning", "Brases", "Dental Implant" ]
// Setting instance varibale type
var type = 0 { didSet { update() } }
func update () {
didChange.send(())
}
}
struct ContentView: View {
#ObservedObject var booking = Booking() //bindableObject in old swift version
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $booking.type, label: Text("Select a Booking Type")) {
ForEach(0 ..< Booking.types.count){
Text(Booking.types[$0]).tag($0)
}
}
}
}
.navigationBarTitle(Text("Darpan Dental Home"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The Complete output Log is here:
*> 2020-03-29 09:22:09.626082+0545 DD[1840:76404] [TableView] Warning
once only: UITableView was told to layout its visible cells and other
contents without being in the view hierarchy (the table view or one of
its superviews has not been added to a window). This may cause bugs by
forcing views inside the table view to load and perform layout without
accurate information (e.g. table view bounds, trait collection, layout
margins, safe area insets, etc), and will also cause unnecessary
performance overhead due to extra layout passes. Make a symbolic
breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch
this in the debugger and see what caused this to occur, so you can
avoid this action altogether if possible, or defer it until the table
view has been added to a window.*
**where is this UITableViewAlertForLayoutOutsideViewHierarchy in SwiftUI ? **
extension UIView {
func rootView() -> UIView {
var view = self
while view.superview.isNotNil {
view = view.superview!
}
return view
}
var isOnWindow: Bool {
return self.rootView() is UIWindow
}
}
then you just need to check if your tableView isOnWindow like...
if self.tableView.isOnWindow {
/// do stuff
}
Disclaimer: as the documentation explains, you may need to defer the call which means that there is no warranty your method will be called again so it's your responsibility to perform your update when isOnWindow is true.
Had the same issue, removing tableView.reloadSections fixed it. This was the line of code causing the warning:
iOS 13:
tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
in iOS 14, removing tableView.reloadSections did not fix the warning.
Or maybe your code (like mine) has nothing wrong with it and this message just randomly starts popping up. In that case, do a clean on your project, restart Xcode and watch the message magically go away!
Please check following function
override func viewWillLayoutSubviews()
For anyone that has this issue with a UISplitViewController and a UITableView inside the detail view controller, you can try subclassing and override layoutSubviews like this (From this thread):
class CustomTableView: UITableView {
override func layoutSubviews() {
if (self.window == nil) {
return
}
super.layoutSubviews()
}
}
Instead of reloading the rows inside viewDidAppear, this is what it worked for me:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.tableView.reloadRows(at: [indexPath], with: .none)
}
Also if you are using DiffableDataSource and you are selecting an indexPath manually for example, you need to do it on the completion block of the apply snapshot method:
dataSource.apply(snapshot, to: section, animatingDifferences: false, completion: {
// select the indexPath programmatically or do UITableView UI stuff here.
})
... the table view or one of its superviews has not been added to a window ...
To resolve the issue we need to check tableView.window property:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
updateTableViewRows()
}
func dataChanged() {
updateTableViewRows()
}
func updateTableViewRows() {
if tableView.window == nil {
// TODO: just update data source
} else {
tableView.performBatchUpdates {
// TODO: update data source
// TODO: update table view cells
}
}
}
}
The idea is to not call performBatchUpdates and related functions while tableView.window is nil.

Pull to refresh and Alamofire using Swift 3

I am using Alamofire to get data from a web URL(JSON). I am trying to implement pull to RefreshControl into my project. I have done it but don't know if it is correct or if the data is getting updated when refreshed. My code is:
var refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(self.refreshData), for: UIControlEvents.valueChanged)
func refreshData() {
Alamofire.request("https://www.example.com/api").responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
self.tableView.reloadData()
self.refresh.endRefreshing()
})
}
Is this correct?
You are doing correctly but you need reload tableView and stop UIRefreshControl on main thread.
DispatchQueue.main.async {
self.tableView.reloadData()
self.refresh.endRefreshing()
}
Note: Instead of setting separatorStyle always on API request you need to set it once with viewDidLoad or with Interface builder.

TableView Segue to new ViewController does not work twice

I have a TableViewController in which selecting a row makes a network call, shows an activityIndicator, and in the completion block of the network call, stops the indicator and does a push segue.
In testing, I found that when going to the new view controller, going back, and selecting another row, it shows the activity indicator, but never stops or calls the push segue. The code for didSelect:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.userInteractionEnabled = false
self.searchController?.active = false
self.idx = indexPath
let cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell
cell.accessoryView = self.activityIndicator
self.activityIndicator.startAnimating()
self.networkingEngine?.getObjectById("\(objectId)", completion: { (object) -> Void in
if object != nil {
self.tableView.userInteractionEnabled = true
self.chosenObject = object
self.activityIndicator.stopAnimating()
self.tableView.reloadRowsAtIndexPaths([self.idx], withRowAnimation: .None)
self.tableView.deselectRowAtIndexPath(self.idx, animated: true)
self.performSegueWithIdentifier("segueToNewVC", sender: self)
}
else {
}
})
}
and my network call using Alamofire
func getObjectbyId(objectId: String, completion:(Object?) -> Void) {
Alamofire.request(Router.getObjectById(objectId: objectId))
.response { (request, response, data, error) -> Void in
if response?.statusCode != 200 {
completion(nil)
}
else if let parsedObject = try!NSJSONSerialization.JSONObjectWithData(data as! NSData, options: .MutableLeaves) as? NSDictionary {
let object = parsedObject["thing"]
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(object)
})
}
}
}
So I made breakpoints, and it actually is going into the completion block the second time and calling it to stop indicator, reload that row, deselect the row, re-enable the tableView userInteraction, and perform the segue. It calls my prepareForSegue as well, but as soon as it finishes, it just sits with the indicator still spinning, and the RAM usage skyrockets up to almost 2GB until the simulator crashes.
I believe it has to do with multi-threading but I can't narrow down the exact issue since I'm putting my important stuff on the main thread.
The problem had to do with making the accessoryView of the cell an activityIndicator and then removing it and reloading it all while segueing away. I couldn't figure out how to keep it there and stop the multi-threading issue but I settled for a progress AlertView. If anybody has a solution, I'd love to know how this is fixed.

UIRefreshControl not refreshing when triggered programmatically

I am trying to show a refresh control right when the view loads to show that I am getting getting data from Parse. The refresh control works as it should when the app is running, but I cannot get it to fire programmatically from anywhere in my app.
This is the code that does not appear to run:
override func viewDidAppear(animated: Bool) {
self.refresher.beginRefreshing()
}
Not only does this not run, but having the code in the app changes the attributes of the refresh control. When I have this code in the app, and show the refresher from user interaction, the refresh control does not have its attributed title as it usually does nor does it run the code that it should.
I needed to add a delay between setContentOffset and the self.refreshControl?.sendActions(for: .valueChanged) call. Without the delay, the refreshControl's attributedTitle would not render.
This works in iOS 10 (Swift 3):
self.tableView.setContentOffset(CGPoint(x:0, y:self.tableView.contentOffset.y - (self.refreshControl!.frame.size.height)), animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: {
self.refreshControl?.sendActions(for: .valueChanged)
})
Here's an extension working on 10.3:
extension UIRefreshControl {
func refreshManually() {
if let scrollView = superview as? UIScrollView {
scrollView.setContentOffset(CGPoint(x: 0, y: scrollView.contentOffset.y - frame.height), animated: false)
}
beginRefreshing()
sendActions(for: .valueChanged)
}
}

Resources