Here is the scenario:
OrderVC have a table view on which if you right swipe it shows some
options. In which one of the option is Checkout.
When user taps on Checkout it opens up CheckoutVC which has a parent class OrderVC.
Here user can add some text and can attach multiple images and can also save this data as draft which is achieved using core data. But when user submit the bill I'm using AFNetworking to call web api and upload images using AFMultipartFormData. All of this process is taking place on a background thread i.e.dispatch_async
I can't update UI in dispatch_get_main_queue because methods are calling other method from within see this question it'll clear this point. So it calls the update UI right after first method is finished.
Question
As long as background thread is working it should show activity indicator on the cell. When it's finished and the response is success in CheckoutVC it should reload the tableView of OrderVC.
Solution I triedI tried to run a for loop in allOrderID which are the ID's I get via web api hit of active orders. Then I made a call to MR_findFirstByAttribute to find if any of the fetched OrderID exist in drafts. There is an attribute isSending in DraftOrderInfo entity which is a BOOL and I truns it to true when checkout enters background thread. So if isSending is true I show the activity indicator in place of a UIView I created.
for (NSString *orderID in allOrderId) {
DraftOrderInfo *dpi = [DraftOrderInfo MR_findFirstByAttribute:#"orderID" withValue:orderID];
if (dpi.isSending) {
orderCell.rightUtilityButtons = nil;
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityView.center = CGPointMake(orderCell.orderStatusIndicatorBadgeView.frame.origin.x-2, orderCell.orderStatusIndicatorBadgeView.frame.origin.y-8);
[activityView startAnimating];
[orderCell.orderStatusIndicatorBadgeView addSubview:activityView];
}
}
The output I get is that when OrderVC is loaded it started showing activity indicator on all the cells.
First, your following point is not valid. Read the comments on the question:
can't update UI in dispatch_get_main_queue because methods are calling
other method from within see this question it'll clear this point. So
it calls the update UI right after first method is finished.
Back to the problem. There is multiple good practices to use. One of them:
Add the UIActivityIndicator to the UITableViewCell at design time(nib or storyboard) as done with the UILabel(s) and other controls.
On submitting the checkout. Change the isSending status to YES and inform the parent UIViewController to reload the table data by calling reloadData method on the UITableView.
In cellForRowAtIndexPath or willDisplay:forRowAt method set the state of the activity indicator as animating or stopped based on the isSending value. This way even if reloading the table or scrolling up and down, the activity indicator will have its state right.
Whe the submitting finishes. Change the isSending state to YES and inform your parent ViewController to reload the table by calling reloadData method on the UITableView. And since the checkin finishes in a background thread you should inform your parent ViewController using dispatch_get_main_queue. read the comments on the question you added to your question. This point you mention regarding the dispatch_get_main_queue is wrong.
Related
I am working in Swift. When a user presses a UIButton it calls a function ButtonPressed(). I would like ButtonPressed() to do two things:
Update the UIView by removing the current buttons and texts, then uploading some new text.
Call function TimeConsumingCalculation(). TimeConsumingCalculation is the complicated part of my app and does some calculations which take about 20 seconds or so to complete.
Right now, I have the code in the basic order:
ButtonPressed(){
self.Button.removeFromSuperview()
TimeConsumingCalculation()
}
However, it will not remove the button or do any other UI updates or additions until after the TimeConsumingCalculation is complete. I have read and attempted a few guides on closures and asynchronous functions, but have had no luck. Is there a special property with UIView that is causing it to be updated last?
As a side note - I have already attempted putting all UI actions in a separate function and calling it first. It doesn't work. The time consuming function does not take any variables from the buttons or UI or anything like that.
Thanks!
It seems like timeConsumingCalculation() is blocking the main queue, which is in charge of UI updates. Try calling it like this instead and use the isHidden property to hide the button instead of removing it from the view completely.
ButtonPressed(){
self.Button.isHidden = true
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
self.timeConsumingCalculation()
}
}
here you call timeConsumingCalculation() asynchronously on a background thread. The quality of service we give it is userInitiated, read more about quality of service classes here
I'm using a UIRefreshControl to enable the pull-to-refresh gesture on a table view.
I have used the storyboard te setup the RefershControl and in my TableViewController is use the following code to bound the method to the RefeshControl:
self.refreshControl?.addTarget(self, action: Selector("getData"), forControlEvents: UIControlEvents.ValueChanged)
At the end of the getData() method I call the reloadData() method on the tableview and the stopRefreshing() method on the refreshcontrol.
This is working fine. I can pull to refresh and the table gets updated.
Next thing I want is to start the RefreshControl when the TableViewController gets loaded. To show the user that the app is getting the data.
I tried to manually start the folowing code:
self.refreshCorntrol?.beginRefreshing()
getData()
It reloads the data but the animation is not working like it should.
The table stays empty. Then when all the data is fetched the table is pulled down (like when I manually pull to refresh) en immediately pushed back up.
Anyone know if it is possible to change/fix this?
Two things could be going on.
1. UI Updates must be dispatched on the main thread.
You're updating a tableView using it's .reloadData() method, which is considered an update to the UI. This being said, you must call .reloadData() on the main thread. While this should be done automatically for you already, I have run into some cases where I need to manually move it to the main thread. This can be done using
DispatchQueue.main.async {
// Update UI ie. self.tableView.reloadData()
}
inside your function.
2. Programmatic pull refreshes don't always run for .valueChanged
It is important to call .valueChanged (or, as you have it in your code, UIControlEvents.ValueChanged) when you call the pull refresh function, so that it is aware of what you are refreshing for. When the user pull refreshes, your program already does it, in the forControlEvents segment of your refreshController declaration. However, when you call it manually from your code, it does not do this by default. Instead, you have to pass the action using sendActions. This can be done by using
self.refreshControl?.beginRefreshing()
self.refreshControl?.sendActions(for: UIControlEvents.ValueChanged)
getData()
to call the pull refresh, rather than just calling .beginRefreshing
Afterword
I ran into a similar issue a few days ago, and posted the question on Stack Overflow here (I'm providing attribution in case you can find your answer there, and because it is where I took my first solution for you from).
This is how my application is looking now:
After I perform a database update in my detail controller in view number 7 in the image above as soon as the save button is clicked the details are saved the the database. I'm taken back to tableView number 5 and expect the associated row to show latest updates by calling a special method from the parse.com framework that reloads objects and refreshes the table view e.g. [self loadObjects].
I use an unwind segue. In view 7 I make a connection between the save button and the exit symbol of it's controller window in interface builder and then in tableView number 5 I have my segue method that corresponds to this connect.
Unwind segue method:
-(IBAction)saveDetailsButtonTapped:(UIStoryboardSegue *)segue {
// alert goes here
[self performSelector:#selector(didTapRefreshButton:) withObject:self afterDelay:1.0];
}
This method clears the table and loads the first page of objects:
- (IBAction)didTapRefreshButton:(id)sender {
[self loadObjects];
}
When save is clicked on view number 7 the details are saved to the db and user is bought back to table view number 5 then the method above runs after 1.0 delay. I thought this was ok but didn't feel too right. I tried it on my phone and sometimes the delay wasn't long enough, meaning a failed refresh.
I then decided to try using a UIAlertView delegate method to detect when the ok button of the alertview was pressed and it worked ok most times but then the times I pressed OK to dismiss the alert really quickly upon arriving back on the view and the data wasn't reloaded.
Is there a better solid reliable way to refresh my data?
I need some way of knowing that the database update was successful and only then run the [self loadObjects] method and maybe do that automatically.
I have two methods that detect when objects will load (e.g. like when a button has been tapped) and when they have loaded. I have put some spinner code in there to show a spinner while loading is happening and take it away once it's done.
Isn't there some sort of way to queue methods, like some how in one method make it so one thing doesn't happen until another thing has happened?
If so, I'd really appreciate some insight and examples as I could just mark the app as complete but even though I'm not being paid and it's charity work I still have the urge to do my best.
Thanks for your time.
Kind regards
I have put some spinner code in there to show a spinner while loading is happening and take it away once it's done.
You should do something like that here.
I need some way of knowing that the database update was successful and only then run the [self loadObjects] method and maybe do that automatically.
Because you're saving to parse, it should be the parse SDK that tells you when the save is complete. If you're saving in the background (which you should be) then use the save method when provides you with a callback block that is called when the save has completed. This block being called is your trigger to remove the spinner and segue.
Side note :-
Yes, there are several different kinds of queues, most better than using performSelector:..., but there are also other ways of working with asynchronous activities and you should look at the asynchronous activity for guidance. i.e. can I get a callback when this is done, rather than how long should I wait and hope that it is done.
I have a UITableView that requests for more data from the server when the user hits the bottom of the table (similar to the Twitter application). However, I'm trying to use a modal segue to filter out data to the user's desire. In order to properly select which data to filter, I have to load ALL of the data to categorize it. In order to load everything, I am required to send out multiple NSURLConnections to load multiple pages. I am trying to have it so when one completes, the next one starts.
However since the connection completes with connectionDidFinishLoading, I have not figured out a way to send out simultaneous NSURLConnections from within prepareForSegue. I tried using a while loop in prepareForSegue as follows:
while (All of the data is not loaded) {
if (isLoading == NO) {
[self loadMoreResults];
}
}
where "isLoading" is a BOOL declared in my viewcontroller's implementation file. isLoading changes value to YES inside loadMoreResults, and changes back to NO at the end of connectionDidFinishLoading. However, within prepareForSegue, isLoading never changes back from YES to NO.
Is this a multithreading issue? I have done research on other questions and see that NSURLConnection has a class method sendAsynchronousRequest:queue:completionHandler: where the completion handler might help, but I'm unsure how I would use it.
ALSO: I want to continue executing prepareForSegue AFTER the last connection finishes, not right after it sends the request.
Thanks in advance!
Then you should not link the segue directly from the bar button item to the view controller in the storyboard.
Just link a general segue with identifier from the table view controller to the filter view controller.
And from the bar button item, create an action for it from the storyboard so that you can send out multiple NSURLConnections first.
Finally then in your code, after the last connection finishes, call the performSegueWithIdentifier method.
I'm facing some weird behavior in my map based App. I'm fetching some data to display a route using some directions service. It runs in an background thread using GCD. With the data fetched I return to the main thread to update the UI :
dispatch_async(dispatch_get_main_queue(), ^{
[self.mapProvider addToExistingPolyLinePoints:coordinates withTitle:#"line" removeOldOne:NO useCurrentIndex:NO];
[_distanceLabel setText:[NSString stringWithFormat:#"%.2lf km",[self.draggingLogic getOverallDistance]]];
[self.progress setHidden:YES];
});
This all works fine in my RouteViewController. But if I go back to the RootViewController using the back button and reenter the RouteViewController and refetch the whole thing, the UI does not get evaluated. It shows the same behavior as if the UI update is not done in the main thread. The data arrives correct.
I'm wondering if it is some kind of issue regarding the view controller life-cycle of iOS, which I did not got completely. What happens when I push the back button. Obviously the ViewController is not destroyed but if I reenter it will create a new one. Is it possible from the RootViewController to determine if an instance of the target view controller is existing and perform the Segue using it?
Anyway, I'm not sure if this is regarding my issue.
Thanks for any ideas
If I understand right what you wrote, you create a new controller every time you "enter" but the dispatching block always refer to the first one you create, so the new one is displayed but the old one get the notifications...
There are lots of way to avoid this, depends on your implementation, but a simple solution may be keep a (strong) reference to the map view controller in a property of the root view controller: if it's nil (first time) you create the map controller and do all the needed stuffs, else you'll simply show it, without the creation part.
example code, in .h:
#property (strong,nonatomic) MyMapController* mapController;
in .m:
if (!self.mapController)
{
// create the controller and the update handler...
self.mapController = ... //created object
}
// show it and everything...
hope this help
You are needed to do the stuff given here....
you create a new controller every time you "enter" but the dispatching block always refer to the first one you create, so the new one is displayed but the old one get the notifications...
Ex-code, in Interface file :
#property (strong,nonatomic) MyMapProvider* mapProvider;
And in implementation file :
if (!self.mapProvider)
{
self.mapProvider = ... //create object
}
// do your stuff..