Adding an activity indicator in another method to avoid hanging - objective-c

I have implemented Reachability.h from Apple into my demo app. The problem is that I noticed that my app stalls while checking connection.
So, I added an Activity Indicator (From MBProgressHUD) . But the indicator does not animate. It stalls with the application too.
So, I thought of putting the activity indicator inside another thread different than the main thread but still it is not animating.
Note: I'm not very experienced
UPDATE: Also, I have tried the native Activity Indicator with no luck.
- (void)anotherThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
// Set determinate mode
HUD.mode = MBProgressHUDModeDeterminate;
HUD.delegate = self;
HUD.labelText = #"loading";
// myProgressTask uses the HUD instance to update progress
[HUD showWhileExecuting:#selector(crazyCounter) onTarget:self withObject:nil animated:YES];
[pool release];
}

UI code should be kept in main thread. So instead of putting the activity indicator into another thread, you may want to use GCD (grand central dispatch) to throw your checking connection code in another thread. When it finishes, you can then remove or hide your activity indicator.
PS. I'm not quite sure what MBProgressHUD does, but you do want to make sure you have something like [activityIndicator startAnimating]. At least for normal activity indicators, you need to manually turn it on.

Related

This application is modifying the autolayout engine from a background - Why?

Since then I have updated Xcode(7.1) I receive (after calling the Game Center leaderboard) this error:
This application is modifying the autolayout engine from a background
thread, which can lead to engine corruption and weird crashes. This
will cause an exception in a future release.
I have this code to call my leaderbord:
- (void)showLeaderboard{
GKGameCenterViewController* gameCenterController = [[GKGameCenterViewController alloc] init];
gameCenterController.viewState = GKGameCenterViewControllerStateLeaderboards;
gameCenterController.gameCenterDelegate = self;
[self.view.window.rootViewController presentViewController:gameCenterController animated:YES completion:nil];
}
My application does not crash but it is annoying to have this error every time when I call the leaderbord. How I can fix this? Do you have any solutions? Thank you for helping!

UITab freeze in iOS

I am developing an iOS 5.1 application on Xcode 4.2.
I have a uitablcontroller with different tabs. My problem is when a tab is clicked , the application 'freezes' for few seconds and does all the codes it's meant to do, but it does not load the UIAlertView first as it should be.
I have the UIAlertView declared in the viewDidLoad.
Here is a code snippet:
- (void)viewDidLoad
{
NSLog(#"##### VIEW DID LOAD 1 #####");
// Display Alert: Loading
alertView = [[UIAlertView alloc] initWithTitle:#"Loading"
message:#"\n"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(139.5, 75.5); // .5 so it doesn't blur
[alertView addSubview:spinner];
[spinner startAnimating];
[alertView show];
[super viewDidLoad];
NSLog(#"##### VIEW DID LOAD 2 #####");
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self callMainMethod];
}
When the tab is clicked, I can see that the first NSLog's are displayed in the Log, and then the main method is called, but the UIAlertview is not displayed.
When viewDidLoad is running, it may be that the frame of the associated UIView has zero size. I don't know, but the UIAlertView may be trying to present itself in this zero-size frame. Does it make sense if you present the UIAlertView in viewDidAppear?
If [self callMainMethod] is taking lots of compute power, then the display might not be updated until it finishes. You could try moving it to viewDidAppear. You could also try delaying it, so that the main run loop for the UI thread, the thread that the display is updated on and the thread that executesviewDidLoad and all the other view... methods, has time to complete everything and become idle before you start the heavy processing. It's only when the run loop has done all the processing it can that it starts actually to update the display. Like this:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^{
[self callMainMethod];
}
The documentation for that is at http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
If that suspicion is correct, you should then get the UIAlertView popping straight up, only to have everything go dead for a while, while callMainMethod executes.
I wish I knew how to write, "dispatch this block only after you've managed to finish updating the display with everything up to here", but I don't know how to do that. So the dispatch call above should delay the call to callMainMethod by 200ms, which is usually plenty.
If that works, you should probably start another question, something like "How can I stop the display freezing while I execute this method."

performSelectorInBackground causes random crash when view is dismissing

I'm having some random crashes at this part of my code:
-(void) goBack {
[self performSelectorInBackground:#selector(addActivityIndicator) withObject:nil];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)addActivityIndicator {
#autoreleasepool {
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityView];
[activityView startAnimating];
self.navigationItem.leftBarButtonItem = barButton;
}
}
When I want to exit the screen where these method exists, the other ViewController have to process some data. To inform the user that processing is occurring I add an activity indicator to the left button in my navigation bar.
The problem is that sometimes I get an exc_bad_access in addActivityIndicator method. The frequency is very random, sometimes the XCode shows the error at the end of #autoreleasepool, sometimes at the line self.navigationItem.leftBarButtonItem = barButton;
I imagine that sometimes my viewController is destroyed but the thread is still running and try to access the navigationItem of a object that don't exists anymore. But I'm not sure if that is the problem and I don't know how to fix it.
I'm using ARC in my project and this problem occurs in all iOS versions that I tested.
Please, anyone can explain me what is happening and how can I fix this?
Thanks.
You should never do UIKit stuff in the background.
By calling [self performSelectorInBackground:#selector(addActivityIndicator) withObject:nil]; you are updating the UI on a background thread. You should only ever update the UI on the main thread.
Edit
Based on your comment you are trying to have the UI update before the view pops. The way to do that would be:
[self addActivityIndicator]
[navigationController performSelector:#selector(popViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES] afterDelay:0];
You could also look into dispatch_after

Help with flickering when reloading an openGL scene

I'm starting to feel bad for asking so many questions and not being able to answer anyone's, but as soon as I find some that I can, I will! Confession out of the way...
Besically I have a gameLoop that runs everything in a game that I'm making and everything works fine in the menu and then in the game, but when I quit the game and then reload the menu screen the screen flickers.
Here is my game loop, I hope it provides some insight.
//A game loop that is triggered by a timer with intervals of 1/60 seconds
- (void)gameLoop
{
// we use our own autorelease pool so that we can control when garbage gets collected
NSAutoreleasePool * apool = [[NSAutoreleasePool alloc] init];
thisFrameStartTime = [levelStartDate timeIntervalSinceNow];
deltaTime = lastFrameStartTime - thisFrameStartTime;
lastFrameStartTime = thisFrameStartTime;
// add any queued scene objects
if ([objectsToAdd count] > 0)
{
[sceneObjects addObjectsFromArray:objectsToAdd];
[objectsToAdd removeAllObjects];
}
// update our model
[self updateModel];
// send our objects to the renderer
[self renderScene];
// remove any objects that need removal
if ([objectsToRemove count] > 0)
{
[sceneObjects removeObjectsInArray:objectsToRemove];
[objectsToRemove removeAllObjects];
}
[apool release];
if (needToLoadScene)
{
[sceneObjects removeAllObjects];
[self loadScene];
}
if (needToEndScene)
{
[sceneObjects removeAllObjects];
[self stopAnimation];
//We'll need to add unloading sounds later on
[inputController endScene];
[self renderScene];
needToEndScene = NO;
}
}
The only other thing that I should add is that the view is controlled by a class MusicAndViewController which I use as a view and then add subsequent views to. The menu and game views are actually the same openGL view but I render a clean view before switching to the other view
Anyone who has a similar problem to what I have had what solved it for me is this.
When setting a timer I had to override the setter so that it invalidated and then set the timer. On my gameScene I hadn't done this so when I make the timer = nil it continues to fire (as it hadn't been invalidated before setting it to nil, and was still running) and then cause a flickering on the next loaded scene (the menu)

Replace UIBarButtonItem with UIActivityIndicatorView not working

I want to replace refresh button with activity indicator when the user press the refresh button and after the tableview is refreshed, i want to change it back to refresh button. But when I press the refresh button, it didn't change to activity indicator but the refresh button is highlighted until the data reloading is finished.
the code is as below. Did I miss something?
-(void) reloadNewsStarted{
UIActivityIndicatorView *activityIndicatorRightBarItem = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[activityIndicatorRightBarItem startAnimating];
UIBarButtonItem *activityItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicatorRightBarItem];
[activityIndicatorRightBarItem release];
self.navigationItem.rightBarButtonItem = activityItem;
[activityItem release];
[self reloadNewsEnded];
}
-(void) reloadNewsEnded {
//reload data process
UIBarButtonItem *reloadNewsBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:#selector(reloadNewsStarted)];
reloadNewsBtn.style = UIBarButtonItemStyleBordered;
self.navigationItem.rightBarButtonItem = reloadNewsBtn;
[reloadNewsBtn release]; }
Instead of writing
[self reloadNewsEnded];
Please write
[NSThread detachNewThreadSelector:#selector(reloadNewsEnded) toTarget:self withObject:nil];
this line start new thread in background so the activity indicator & the data reload will be done simultaneously in two thread.
why is this line at the end of the reloadNewStarted method
[self reloadNewsEnded];
it appears to just undo the changes to the button? You should be waiting until the action is complete before calling it
Changing the button isn't going to take effect until the run loop regains control from your code. It sounds like your reload operation is synchronous and blocks the event queue, which won't allow that to happen. If your processing takes a noticeable amount of time, you need to use either a background thread or asynchronous handling on the main run loop (for example, by using NSURLConnection to manage a network task and callbacks) so you don't block.