Assuming this is called from the main thread, there isn't really any reason to call , because the default run loop should already be running.CFRunLoopRun
The way you're using will not block the calling thread. It may spawn additional threads internally, but you don't really have to care about that. NSURLConnection will return pretty much immediately and your delegate methods will be called later (when a response is received, data is loaded, etc.).initWithRequest:delegate:
You're doing well. There's not problem to use CoreFoundation when you cannot achieve your goal with Foundation. As CoreFoundation is C, it's easier to mess up with memory management but there is no intrinsic danger in using rather than CFRunLoop (sometimes it may even be safer: NSRunLoop API are thread-safe whereas CFRunLoop isn't).NSRunLoop
If you want to stop your , you can run it using NSRunLoop. runMode:beforeDate: returns as soon as an input source is processed so you don't need to wait until the timeout date is reached.runMode:beforeDate:
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
NSDate *date = [NSDate distantFuture];
while ( !runLoopIsStopped && [runLoop runMode:NSDefaultRunLoopMode beforeDate:date] );
Then, to stop the run loop, you just need to set to runLoopIsStopped.YES
For a command line interface use this pattern and add a completion handler to your AsyncNetworkingStuff (thanks to Rob for code improvement):
print("start")
let runLoop = CFRunLoopGetCurrent()
startAsyncNetworkingStuff() { result in
CFRunLoopStop(runLoop)
}
CFRunLoopRun()
print("end")
exit(EXIT_SUCCESS)
Please don't use ugly loops.while
Update:
In Swift 5.5+ with async/await it has become much more comfortable. There's no need anymore to maintain the run loop.
Rename the file as something else and use the main.swift attribute like in a normal application.@main
@main
struct CLI {
static func main() async throws {
let result = await startAsyncNetworkingStuff()
// do something with result
}
}
The name of the struct is arbitrary, the static function is mandatory and is the entry point.main