Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 458
Frank van Vliet Avatar asked Feb 28 '11 10:02

Frank van Vliet


2 Answers

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.

like image 50
Antwan van Houdt Avatar answered Nov 11 '22 15:11

Antwan van Houdt


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

like image 6
ayalcinkaya Avatar answered Nov 11 '22 15:11

ayalcinkaya