Reachability code blocking main thread
I'm currently working on开发者_如何学编程 an app that requires me to check for reachability.
Owing to that, I started looking stuff up and found DDG and Apple's code. I decided to go with Apple's latest reachability code.
I imported that, and as suggested in Apple's sample, I came up with the following way to register:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:kReachabilityChangedNotification object:nil];
//check for local connection and start notifier
client = [[Reachability reachabilityForInternetConnection] retain];
[client startNotifier];
//check for server connection and start notifier
server = [[Reachability reachabilityWithHostName:SERVER_HOST_NAME] retain];
[server startNotifier];
//check for other server and start notifier
otherServer = [[Reachability reachabilityWithHostName:OTHER_SERVER_HOST_NAME] retain];
[otherServer startNotifier];
What I observed when I ran the app was that this code started blocking the UI (blocking the main thread). I could not interact with other UI elements till the host name was resolved. Now I know that Apple has stated a warning about DNS resolution and making it asynchronous.
My question would be, how do I go ahead and make it asynchronous?
Do I spawn another thread and keep it running so as to not "release" the Reachability object?
Thanks in advance for your help! :)
Okay. Well, I found out what the problem was. >_<
The code posted above does indeed work asynchronously.
However, the code that I had written under notificationHandler:
was making a synchronous call to a service. It was written by someone else, owing to which it took me some time to figure out that that was the source of the UI freeze. However, problem has been solved. I thought I'd write this post so as to give a closure to this question. :)
Thanks again!
精彩评论