Wednesday, May 1, 2013

NSURLConnection scheduleInRunLoop example ios


scheduleInRunLoop :forMode:

Determines the run loop and mode that the connection uses to send messages to its delegate.
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
Parameters of [NSURLConnection scheduleInRunLoop]
aRunLoop
The NSRunloop instance to use for delegate messages.
mode
The mode in which to supply delegate messages.
Discussion of [NSURLConnection scheduleInRunLoop]
By default, a connection is scheduled on the current thread in the default mode when it is created. If you create a connection with the initWithRequest:delegate:startImmediately: method and provide NO for the startImmediately parameter, you can schedule the connection on a different run loop or mode before starting it with the start method. You can schedule a connection on multiple run loops and modes, or on the same run loop in multiple modes.
You cannot reschedule a connection after it has started.
It is an error to schedule delegate messages with both this method and the setDelegateQueue:method.
Example of [NSURLConnection scheduleInRunLoop]
self.connection = [[NSURLConnection alloc] initWithRequest:self.urlRequest
                                                              delegate:self startImmediately:NO];

[self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

[self.connection start];
Example of [NSURLConnection scheduleInRunLoop]
// all the setup comes here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSRunLoop *loop = [NSRunLoop currentRunLoop];
    [connection scheduleInRunLoop:loop forMode:NSRunLoopCommonModes];
    [loop run]; // make sure that you have a running run-loop.
});
Example of [NSURLConnection scheduleInRunLoop]
NSURLRequest *request = ...
NSURLConnection *connection = [[NSURLConnection alloc]
                               initWithRequest:request
                               delegate:self
                               startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
            forMode:NSRunLoopCommonModes];
[connection start];