Tom
Tom

Reputation: 346

Why is app crashing when showing UIAlertView?

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;
}

Upvotes: 3

Views: 203

Answers (1)

eric
eric

Reputation: 4951

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];

Upvotes: 2

Related Questions