Jonny Jonny - 6 months ago 33
iOS Question

DNS lookup asynchronously

There is a piece of code that does DNS lookups using CFHostStartInfoResolution(). However this is synchronously and thus blocks anything before it returns - it's bad and I also think it causes crashes due to timeouts when connection is weak (when its bad it fails out safely directly)

So I want to do this asynchronously, as it's supposed to in the docs https://developer.apple.com/library/ios/documentation/CoreFoundation/Reference/CFHostRef/Reference/reference.html

Specifically it says:


If you want to resolve the host asynchronously. call CFHostSetClient
to associate your client context and user-defined callback function
with the host. Then call CFHostScheduleWithRunLoop to schedule the
host on a run loop.


However this put me off because I haven't coded C in ages and can't get callbacks and runloops/threading right.

How am I supposed to call CFHostSetClient, CFHostScheduleWithRunLoop, and how do I implement those callbacks? Do I need to start a new thread?

Answer

Should be something like this

CFHostSetClient(host, callbackFunction, hostContext);
CFHostScheduleWithRunLoop(host, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFHostStartInfoResolution(host, kCFHostAddresses, 0);

And callbackFunction

void callbackFunction(CFHostRef theHost, CFHostInfoType typeInfo, const CFStreamError *error, void *info) {
    // Do something
}

You don't need to start a new thread, system will do it for you.