Wednesday, May 1, 2013

NSURLConnection unscheduleFromRunLoop example ios


unscheduleFromRunLoop :forMode:

Causes the connection to stop sending delegate messages using the specified run loop and mode.
- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
Parameters of [NSURLConnection unscheduleFromRunLoop]
aRunLoop
The run loop instance to unschedule.
mode
The mode to unschedule.
Discussion of [NSURLConnection unscheduleFromRunLoop]
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 instead schedule 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. Use this method to unschedule the connection from an undesired run loop and mode before starting the connection.
You cannot reschedule a connection after it has started. It is not necessary to unschedule a connection after it has finished.
Example of [NSURLConnection unscheduleFromRunLoop]
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // finished downloading the data, cleaning up
    self.response = nil;

    // Delegate is responsible for releasing data
    if (self.delegate)
    {
        NSData *theData = [self.data retain];
        DELEGATE_CALLBACK(didReceiveData:, theData);
    }
    [self.urlconnection unscheduleFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [self cleanup];
}
Example of [NSURLConnection unscheduleFromRunLoop]
NSURL *url = [NSURL URLWithString:notePicUrl];

            NSURLRequest *urlRequest = [NSURLRequest  requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
            //NSOperationQueue *queue = [[NSOperationQueue alloc] init];

            NSURLConnection* _connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
            self.port = [NSPort port];                                                                                                       
            self.runLoop = [NSRunLoop currentRunLoop];                                                                                       
            [self.runLoop addPort:self.port forMode:NSDefaultRunLoopMode];
            [_connection scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode];
            [_connection start];
            while (self.finished != YES ) {
                [self.runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow: 0.1]]; 
            }
            [self.runLoop removePort:[self port] forMode:NSDefaultRunLoopMode];
            [_connection unscheduleFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];