Checking for NSRunLoop and using appropriate NSURLConnection method
cocoa, foundation, objective-c
Solution
Alternately, is there a way to always use the asynchronous method but force the application to not exit until the async request has finished?
Easy as pie:
int main(int argc, char *argv[])
{
// Create request, delegate object, etc.
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:delegate
startImmediately:YES];
CFRunLoopRun();
// ...
}
I use `CFRunLoopRun()` here because it's possible to stop it later, when the delegate has determined that the connection is done:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// This returns control to wherever you called
// CFRunLoopRun() from.
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Error: %@", error);
CFRunLoopStop(CFRunLoopGetCurrent());
}
The other option is to use `-[NSRunLoop runUntilDate:]` in a while loop, and have the delegate set a "stop" flag:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:delegate
startImmediately:YES];
while( ![delegate connectionHasFinished] ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1];
}
Problem
I'm working on a personal project and ran into the asynchronous nature of NSURLConnection last night. I'm building a library that is going to interface with a restful api. I'm anticipating reusing this library, in both Foundation command line tools as well as Cocoa applications. Is there a way I can either check if the runloop is available to call the synchronous method if it is, and send a synchronous request if it is not (in the event of being used in a command line tool). Alternately, is there a way to always use the asynchronous method but force the application to not exit until the async request has finished? I noticed this but I'd rather not have to put the call to run outside of the library. Thanks for any help