Why is app crashing when showing UIAlertView? - iphone

I've implemented the Reachability function in a method that handles all the server requests. I can see through NSLogs that the function works perfectly. However there is never a "pause" within the method which means I can't use the UIAlertView without crashing the program.
I might be going at this the completely wrong way, but I can't find anything else...
Does anybody have an idea of how to get a notification to show somehow?
Thanks in advance
CODE:
-(id) getJson:(NSString *)stringurl{
Reachability * reach = [Reachability reachabilityWithHostname:#"www.google.com"];
NSLog(#"reached %d", reach.isReachable);
if (reach.isReachable == NO) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Passwords don't match."
message:#"The passwords did not match. Please try again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}else{
id x =[self getJsonFromHttp:stringurl];
return x;
}
return nil;
}

After moving the discussion to a chat, we discovered that your UIAlertView was being called from a background thread. Never do anything related to updating the UI (User-Interface) in a background thread. The UIAlertView updates the UI by adding a little pop-up dialog, so it should be done on the main thread. Fix by making these changes:
// (1) Create a new method in your .m/.h and move your UIAlertView code to it
-(void)showMyAlert{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Passwords don't match."
message:#"The passwords did not match. Please try again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
// (2) In -(id)getJson replace your original UI-related code with a call to your new method
[self performSelectorOnMainThread:#selector(showMyAlert)
withObject:nil
waitUntilDone:YES];

Related

Prevent AFNetworking Reachability Status Getting Called at First Launch for iOS

I just want to know how to prevent my alert view from appearing everytime I open my application that's already connected to the internet. I'm using ARC if that helps.
This is the code I have in my didFinishLaunchingWithOptions method inside my AppDelegate:
__weak id myself = self; // to silence warning for retain cycle
_httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://apple.com"]];
[_httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
{
// Not reachable
NSLog(#"Not connected to the internet");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Not connected to the internet" delegate:myself cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi:
{
NSLog(#"Connected to the internet via WiFi");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Connected to the internet via WiFi" delegate:myself cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN:
{
NSLog(#"Connected to the internet via WWAN");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Connected to the internet" delegate:myself cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
break;
}
default:
break;
}
}];
Echoing #D80Buckeye: just don't pop an alert for reachability. It's completely unnecessary, and doesn't add anything to the user experience (it's not like the user can do anything to fix a lack of reachability like that). If anything, you could show a non-modal indication of network reachability.
How about creating a global flag
static BOOL g_FirstTime = YES;
and check it before displaying alert view
if (g_FirstTime) {
g_FirstTime = NO;
break;
}
NSLog(#"Connected to the internet via WiFi");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Connected to the internet via WiFi" delegate:myself cancelButtonTitle:nil otherButtonTitles:#"Dismiss", nil];
[alert show];
break;
Without knowing the scope of your project it's hard to make a solid suggestion. My whole-hearted suggestion is that you do NOT want to do a pop-up every time the end user bounces back on the network. If you have code implemented that is reliably detecting a refreshed network connection, if I were you, I would put some sort of subtle (but obvious) on-screen indicator like a small icon/image or maybe even a UILabel that says "connected" or "disconnected" or whatever verbiage works for you. As others have suggested I would completely steer clear of instantiating a pop-up of any sort for that alert.
Regarding the code itself - get very familiar with View Controller Programming and iOS App Programming Guide. Between those two documents you can properly map out how to detect and react to when your app comes in and out of the background state, when it launches, when it becomes active, when your views appear/load, etc. Combine those methods & calls with some global state-driven variables and you should be well on your way.
Bottom line is you want to get familiar with those app state documents as well as [[NSNotificationCenter defaultCenter] addObserver:<#(id)#> selector:<#(SEL)#> name:<#(NSString *)#> object:<#(id)#>]
Let me know if that doesn't make sense.

UIAlertViewDelegate not acting as expected

I have a very simple process running where after each round of a simple game the scores are calculated, labels updated and all the normal, very simple stuff. I have a UIAlertView that informs the player of how s/he performed. I use a UIAlertViewDelegate to postpone all the updates, resetting of controls etc. till after the UIAlertView is dismissed. The methods are [startNewRound],[startOver] and [updateLabels]. It's fairly obvious what they all do. Anyway, when the user hits round ten, I've made another UIAlertView that informs the player that the game has ended and shows the overall score. Again, I hoped to use a delegate to postpone the resets till after the AlertView is dismissed. The only problem is, with the endGame AlertView, it seems to be using the first AlertView's delegate method causing the game to continue with a new round and not start from the beginning. I hope this makes sense. Anyway, here are snippets of my code.
if (round == 10){
UIAlertView *endGame = [[UIAlertView alloc]
initWithTitle: #"End of Game"
message: endMessage
delegate:self
cancelButtonTitle:#"New Game"
otherButtonTitles:nil];
[endGame show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: title
message: message
delegate:self
cancelButtonTitle:#"Next"
otherButtonTitles:nil];
[alertView show];
}
And then the delegate methods:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self startNewRound];
[self updateLabels];
}
- (void)endGame:(UIAlertView *)endGame didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self startOver];
}
So there it is. As I mentioned, the endGame AlertView appears to be using alertView's delegate, thus not activating the [self startOver] method. All the methods are working, it's just the AlertView is using the incorrect delegate method. Regards, Mike
Change your code like this,
if (round == 10){
UIAlertView *endGame = [[UIAlertView alloc]
initWithTitle: #"End of Game"
message: endMessage
delegate:self
cancelButtonTitle:#"New Game"
otherButtonTitles:nil];
endGame.tag = 111;
[endGame show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle: title
message: message
delegate:self
cancelButtonTitle:#"Next"
otherButtonTitles:nil];
alertView.tag = 222;
[alertView show];
}
and delegate method as,
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 111)
{
[self startNewRound];
[self updateLabels];
}
else if(alertView.tag == 222)
{
[self startOver];
}
}
You cant have two delegate method for dismisswithbuttonindex, you need to handle this situation with tag.
Give both alert view a different tag and check it on delegate object. Thus you can differentiat the both alert view.

Executing a snippet of code in the AlertView OK button declaration

in my Alert View, there is two button, OK and Cancel. When the user click the OK button, the delegate method dismissWithClickedButtonIndex:animated get called, and if the index is 0, then i get called to a method to execute some code:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Are you sure you want to exit"
delegate:self cancelButtonTitle: #"OK"
otherButtonTitles: #"Cancel",nil];
[alert show];
[alert release];//release the reference
Delegate method:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
[self aMethod];
}
}
-(void)aMethod{
//Some useful code
}
Now, what i want to instead of all this, is to execute the code of the aMethod method in the AlertView directly, without referring to A delegate method and a method which get called, something like that:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Are you sure you want to exit"
delegate:self cancelButtonTitle: #"OK" //Put here some useful code
otherButtonTitles: #"Cancel",nil];
Is it possible?
Unfortunately this is not possible at this time (iOS 5.1). The AlertView class does not support blocks.
I made a pair of UIAlertView and UIActionSheet subclasses that do exactly that. Grab them here:
https://github.com/rydermackay/RMActionSheet
Use them like this:
RMAlertView *alertView = [RMAlertView alertViewWithTitle:#"Alert!" message:nil];
[alertView addButtonWithTitle:#"OK"
action:^{
NSLog(#"OK");
}];
[alertView addCancelButtonWithTitle:#"Cancel"
action:nil];
[alertView show];
EDIT:
From your comments it sounds like you're not familiar with blocks. Read this now. Seriously.
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html
This is a good one too:
http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html

Show UIAlertView in background thread

I load data from a webservice in a background thread. Is it safe to show an UIAlertView in the background thread when anything goes wrong or should I show the alert view in the mainthread ?
thanks for the advice
Frank
Never do anything with the GUI except from the main thread. It can cause very weird issues and or crashes you don't want to deal with. Usually the backtraces are also very unhelpful so try to avoid such issues by default.
Therefore use this:
[self performSelectorOnMainThread:#selector(showAlert:) withObject:alertString waitUntilDone:NO];
If you are using grand Central dispatch you could do something like:
dispatch_async(dispatch_get_main_queue(), ^{ /* show alert view */ });
Update:
Swift (3.0+):
DispatchQueue.main.async { // code }
It is sometimes helpful to do this with Notifications you receive as well, I have had instances where they were fired from a different thread.
Update 2:
It looks like apple has added some new tools coming in iOS11/Xcode9 to help debug issues where stuff is called on the incorrect thread.
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message:#"Message" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
});
this code works for me
You could try showing the alert on the main thread by:
UIAlertView *alert = [
[[UIAlertView alloc] initWithTitle:#"the title"
message:#"the message"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil] autorelease];
[alert performSelector:#selector(show)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
[alert release];

IPHONE: UIAlertView called twice in a custom function/IBAction

i have an IBAction which does some processing and within will have a few UIAlertViews (to show alerts). However it seems that the FIRST alert in the paragraph is being called TWICE (once immediately after i clicked and another time after all the other alerts has occured). Additionally, the first time the alert appears, the alert automatically closes even though i have an OK button and the user has not clicked on it. The 2nd time the alert appears, it will require the user to click on OK.
I tried moving the paragraph out from IBAction into its own function but still the problem occurs.
all the alerts in my IBAction/function are the same:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"blah" message:#"blah" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
[alert release];
but the other alerts function normally.
the code looks like this ("blah" is the one being called twice):
-(void)function {
if (......) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"blah" message:#"blah" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert show];
[alert release];
for (int i=0; i<2; i++) {
if (.....) {
//do stuff
} else {
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"blah2" message:#"blah2" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert2 show];
[alert2 release];
}
}
} else {
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:#"blah3" message:#"blah3" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil,nil];
[alert3 show];
[alert3 release];
}
}
please help!
First of all, we need more code to diagnose your problem. What you provide is not sufficient.
Second, I once encountered a similar problem: when a compose an email action is triggered by the user who didn't set up her email account on that device, I asked my app to show an UIAlertView. However, when I tested my code on a real device with such a scenario, two consecutive UIAlertViews showed, one after another, both of which are about the email account not set up issue.
I finally figured out that the iOS system will automatically show an UIAlertView when the email account is not set up while a user tries to compose an email, which is why two UIAlertViews showed up when I only expected one.
Hope that helps.