Dealing with two screens and one activity indicator in iOS - ios

I have 3 screens on my app.First is login. Second is search and third is process the task.
On login i retrieve data from a web service. It returns data in XML format. So the data is considerably large. So i am doing that task on a background thread like this to stop Mainthread freezing up on me:
-(BOOL)loginEmp
{
.....some computation
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
[self getAllCustomerValues];
});
}
-(void)getAllCustomerValues
{
....more computation.Bring the data,parse it and save it to CoreData DB.
//notification - EDIT
NSNotification *notification =[NSNotification notificationWithName:#"reloadRequest"
object:self];
[[NSNotificationCenter defaultCenter] postNotification : notification];
}
//EDIT
//SearchScreenVC.m
- (void)viewDidLoad
{
....some computation
[self.customerActIndicator startAnimating];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(stopActivityIndicator)
name:#"reloadRequest"
object:nil];
}
- (void)stopActivityIndicator
{
[self.customerActIndicator stopAnimating];
self.customerActIndicator.hidesWhenStopped = YES;
self.customerActIndicator.hidden =YES;
NSLog(#"HIt this at 127");
}
So on condition that login was successful, i move to screen 2. But the background thread is still in process( i know because i have logs logging values) . I want an activity indicator showing up here (2nd screen)telling user to wait before he starts searching. So how do i do it?How can i make my activity indicator listen/wait for background thread. Please let me know if you need more info.Thanks
EDIT: so I edited accordingly but the notification never gets called. I put a notification at the end of getAllCustomerValues and in viewDidLoad of SearchScreen i used it. That notification on 2nd screen to stop animating never gets called. What is the mistake i am doing.?Thanks
EDIT 2: So it finally hits the method. I dont know what made it to hit that method. I put a break point. I wrote to stop animating but it wouldn't. I wrote hidesWhenStoppped and hidden both to YES. But it still keeps animating.How do i get it to stop?

Ok, if it is not the main thread, put the following in and that should fix it.
- (void)stopActivityIndicator
{
if(![NSThread isMainThread]){
[self performSelectorOnMainThread:#selector(stopActivityIndicator) withObject:nil waitUntilDone:NO];
return;
}
[self.customerActIndicator stopAnimating];
self.customerActIndicator.hidesWhenStopped = YES;
self.customerActIndicator.hidden =YES;
NSLog(#"HIt this at 127");
}

Could you put your background operation into a separate class and then set a delegate on it so you can alert the delegate once the operation has completed?
I havent tried this, its just an idea :)

You could use a delegate pointing to your view controller & a method in your view controller like:
- (void) updateProgress:(NSNumber*)percentageComplete {
}
And then in the background thread:
float percentComplete = 0.5; // for example
NSNumber *percentComplete = [NSNumber numberWithFloat:percentComplete];
[delegate performSelectorOnMainThread:#selector(updateProgress:) withObject:percentageComplete waitUntilDone:NO];

Related

Perform Action after UIAlertView is showing?

I am uploading a picture to a server. I am using a UIAlertView, AlertView1, which asks the user if he/she wants to upload the picture. If Yes, a second alertview, AlertView2 will show with a progress bar and disappear after the upload is complete.
So, once the user clicks on Yes in AlertView1, I call show AlertView2 and call the method [self uploadPhoto]. So the problem comes that even before AlertView2 has time to show up, the CPU intensive uploadPhoto is running and it delays the AlertView2 from showing up for several seconds. It seems like the AlertView2 finally shows a ways through the uploading process.
How do I start the uploading process only once AlertView2 has shown?
Here is the code
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//Detectss AlertView1's buttonClick
[self.alertView2 show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
//Launches when AlertView1 is dismissed
[self UploadPhoto]
}
-(void)uploadPhoto
{
//CPU/Network Intensive Code to Upload a photo to a server.
}
Set your controller as the delegate of the second alert view, and upload the photo when you receive the didPresentAlertView: message from your second alert.
Use multi-threading to dispatch uploadPhoto to another thread. That way you won't block the main thread while performing costly network operations.
dispatch_queue_t queue = dispatch_queue_create("upload queue", NULL);
dispatch_async(queue, ^{
[self uploadPhoto];
dispatch_async(dispatch_get_main_queue(), ^{
//dismiss alertview2 here
});
});
Call your method [self uploadPhoto] after calling [self.alertView2 show] with a timer using -
[self performSelector:#selector(uploadPhoto) withObject:nil afterDelay:0.3];
It will call your method after a 3 seconds gap after your alert appears.

Codeline triggering randomly dispatch_async

In my secondView I do this:
-(void)viewDidDisappear:(BOOL)animated
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dbq = [[dbqueries alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:#"abc" object:nil];
//disabling a button and turning a progressView in the mainView on
dispatch_async(queue, ^{
//WORK
});
}
The notification disables a button and causes a progressView(in the progressView there is an ActivityIndicator) on the mainView to start.
In the area, where work is done, a method is called 3 to 6 times and if they are all done, I send another notification to the mainView to enable the button and to stop the progressView.
Now the weird thing is, that the button gets enabled at the right time but the progressView stops randomly after a few seconds
- (void)enableStartButton
{
NSLog(#"enableStartButton");
self.startARButton.enabled = YES;
[self.progressView setHidden:YES];
[[self.progressView.subviews objectAtIndex:0] stopAnimating];
}
I really don't know whats going on here, thanks in advance!

Problems with NSNotificationCenter and UIPickerView

I hope I have better luck with someone helping me on this one:
I have a UIPickerView where a user makes a selection and then presses a button. I can gladly obtain the users choice, as shown in my NSLog, and when this is done, I want to send a notification to another view controller that will show a label with the option selected. Well, although it seems everything is done right, somehow it does not work and the label stays intact. Here is the code:
Broadcaster:
if ([song isEqualToString:#"Something"] && [style isEqualToString:#"Other thing"])
{
NSLog (#"%#, %#", one, two);
[[NSNotificationCenter defaultCenter] postNotificationName:#"Test1" object:nil];
ReceiverViewController *receiver = [self.storyboard instantiateViewControllerWithIdentifier:#"Receiver"];
[self presentModalViewController:receiver animated:YES];
}
Observer:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification) name:#"Test1" object:nil];
}
return self;
}
-(void)receiveNotification:(NSNotification*)notification
{
if ([[notification name] isEqualToString:#"Test1"])
{
[label setText:#"Success!"];
NSLog (#"Successfully received the test notification!");
}
else
{
label.text = #"Whatever...";
}
}
I think you have a syntax error in your selector: #selector(receiveNotification). It should probably be #selector(receiveNotification:) with the colon since your method accepts the NSNotification *notification message. Without it, it's a different signature.
The issue is likely that the notification is sent (and therefore received) on a different thread than the main thread. Only on the main thread will you be able to update UI elements (like a label).
See my answer to this question for some insight into threads and NSNotifications.
Use something like:
NSLog(#"Code executing in Thread %#",[NSThread currentThread] );
to compare your main thread versus where your recieveNotifcation: method is being executed.
If it is the case that you are sending the notification out on a thread that is not the main thread, a solution may be to broadcast your nsnotifications out on the main thread like so:
//Call this to post a notification and are on a background thread
- (void) postmyNotification{
[self performSelectorOnMainThread:#selector(helperMethod:) withObject:Nil waitUntilDone:NO];
}
//Do not call this directly if you are running on a background thread.
- (void) helperMethod{
[[NSNotificationCenter defaultCenter] postNotificationName:#"SOMENAME" object:self];
}
If you only care about the label being updated on the main thread, you can perform that operation on the main thread using something similar to:
dispatch_sync(dispatch_get_main_queue(), ^(void){
[label setText:#"Success!"];
});
Hope that was helpful!

iOS - Thread and alertiview

i've an app that when start control updates and other things. If the app find some updates they will ask user if this updates have to be done. If user select YES i want that a spinner appear on main screen until update finish. But when i tap YES my alert view doesn't disappear and remain on screen until update is finished.
Is it possible to create a thread that run on the main thread and stop when update in finished?
Thanks
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex==1) {
[self showActivityViewer];
[self downloadControlAndUpdatePoi];
[self downloadControlAndUpdateItinerari];
[self downloadControlAndUpdateArtisti];
[self downloadControlAndUpdateEventi];
[self hideActivityViewer];
NSLog(#"AGGIORNA");
} else {
NSLog(#"NON AGGIORNARE");
return;
}
}
If the methods
[self downloadControlAndUpdatePoi];
[self downloadControlAndUpdateItinerari];
[self downloadControlAndUpdateArtisti];
[self downloadControlAndUpdateEventi];
are executed synchronously (that means that they return only after having processed completely), so:
[self hideActivityViewer];
is executed only at the very end.
A simple approach to this is scheduling the execution of your methods on the main thread:
[self performSelector:#selector(downloadControlAndUpdatePoi) withObject:nil afterDelay:0];
....
[self hideActivityViewer];
so that those methods are executed only after control has returned to the main loop and the UI has been updated.
Otherwise, you could use:
+ detachNewThreadSelector:toTarget:withObject:
from NSThread, to do more or less the same. In this case I would suggest creating a wrapper method for all of your dowloadAndUpdate... methods, but keep in mind that you can't update the UI from a secondary thread.
In both cases, you should take some care about synchronizing the download... operations with the rest of your workflow after removing the alert view.

[tableView reloadData]; doesn't work until I scroll the tableView

I have a simple app that downloads search results in XML when the user types in a UISearchBar. The download+parsing is threaded and once done it fires an NSNotification to tell the ViewController with the table view to [tableView reloadData];
Here is the code that receives the notification fired once results are in:
- (void)receivedResults:(id)notification {
results = [notification object];
DLog(#"Received %i results",[results count]);
[[self tableView] reloadData];
}
I get the log output "Received 4 results", but the table view doesn't reload the data until I scroll/drag it a couple pixels. I am using the built-in UITableViewCellStyleSubtitle cell style and im not changing the height or ding anything fancy with the table view.
What am I doing wrong?
I was able to get the same thing to work. But the issue was that the reload data needed to be called on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
I think this is more practical than the performSelectorOnMainThread option
Call
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
instead of
[self.tableview reloadData]
My problem was that I was posting a NSNotification from a background thread. To avoid this, simply wrap your postNotificationMethod in a dispatch_async method like this:
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:#"FinishedDownloading" object:result];
});
When this notification will be received, the tableView.reloadData will be called on the main thread.
I have the same problem, and I have tried all the solution I can find on google. But All of them don't work.
At last I found that I add observer before viewDidLoad, and then [self.tableView reloadData] is not working.
First I call the setObserverForUserInfoDatabase in the viewDidLoad of my root navigation view controller. Because I think it was called earlier. The function is like this:
- (void)setObserverForUserInfoDatabase:(NSString *)name {
[[NSNotificationCenter defaultCenter] addObserverForName:name
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[self loadUserInfo];
[self.tableView reloadData];
NSLog(#"User Panel Notification \n %#", self);
}];}
Then I move the code into viewDidLoad of the viewController itself.
- (void)viewDidLoad {
NSLog(#"View Did Load");
[super viewDidLoad];
[self setObserverForUserInfoDatabase:UserInfoDataBaseAvailabilityNotification];
}
And then everything works fine.
I don't know the reason yet. If anyone knows please tell me.
reload your tableView in viewWillLayoutSubviews

Resources