1

Anyone know how to stop run loop of background thread from main thread ?

I have a class which has function for download file from server. From main thread I am calling function sendHttpRequest in background thread to download file from server.

[self performSelectorInBackground:@selector(sendHttpRequest:) withObject:file];

I have used CFRunLoopRun(); to receive callbacks and avoid exiting thread and stopped run loop using CFRunLoopStop(CFRunLoopGetCurrent()); after downloading completed.

But I require to stop downloading when it is in downloading data, how can I stop run loop ?

Any help....

Here is my code:

#import "HTTPHandler.h"

@implementation HTTPHandler

@synthesize fileName;

NSURLConnection *urlConnection;
NSMutableData *receivedData;
NSInteger receivedStatusCode;

- (id)initHttpHandler
{
    self = [super init];
    httpEvent = nil;
    return self;
}

- (void)downloadFile:(NSString *)file
{
    NSLog(@"Download file : %@", file);

    fileName = file;
    NSString *url = [NSString stringWithFormat:@"http://temporaryServerUrl&fileName=%@", fileName];

    NSLog(@"URL : %@", url);

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];

 // create the connection with the request and start loading the data
    [request setHTTPMethod:@"GET"];
    [request setValue:[NSString stringWithFormat:@"text/plain,application/xml"] forHTTPHeaderField:@"Accept"];
    urlConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (urlConnection)
    {
        // Create the NSMutableData to hold the received data.
        receivedData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"HTTP connection failed to download file.");
    }

    NSLog(@"Run loop started");
    CFRunLoopRun();   // Avoid thread exiting
    NSLog(@"Run loop stoped");
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace (NSURLProtectionSpace *)protectionSpace
{
    if ([NSURLAuthenticationMethodHTTPDigest compare:[protectionSpace authenticationMethod]] == NSOrderedSame)
    {
        return YES;
    }
    else
    {
        NSLog(@"Warning: Unsupported HTTP authentication method.");
    }

    return NO;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge (NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0)
    {
        NSURLCredential *newCredential;
        newCredential = [NSURLCredential credentialWithUser:@"admin" password:@"1234" persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    }
    else
    {
        NSLog(@"Going to cancel the authentication challenge.");
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that the user name and password in the preferences are incorrect
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.  
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

    [receivedData setLength:0];
    receivedStatusCode = httpResponse.statusCode;

    if (httpResponse.statusCode == 200)
    {
            NSLog(@"200 ok received");
    }
    else
    {
        // We can also add condition that status code >= 400 for failure.
        NSLog(@"%d status code is received.", httpResponse.statusCode);
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData. receivedData is an instance variable declared elsewhere.
    if ([urlConnection isEqual:connection])
    {
        [receivedData appendData:data];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];

    // inform the user
    NSLog(@"Connection failed! Error domain - %@, error code %d, error discryption - %@", [error domain], [error code], [error localizedDescription]);

    // stop a CFRunLoop from running.
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if ([urlConnection isEqual:connection] && (receivedStatusCode == 200))
    {
        NSString *filePath;
     NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    filePath = [rootPath stringByAppendingPathComponent:fileName];
    NSLog(@"File Path %@", filePath);

        NSString *data = [[[NSString alloc] initWithData:receivedData encoding:NSISOLatin1StringEncoding] autorelease];

        NSLog(@"Data : %@", data);
        [data writeToFile:filePath atomically:YES encoding:NSISOLatin1StringEncoding error:NULL];

    }
    else
    {
    }

    [urlConnection release];
    [receivedData release];

    // stop a CFRunLoop from running.
    CFRunLoopStop(CFRunLoopGetCurrent());
}

@end
Khushbu Shah
  • 1,603
  • 3
  • 27
  • 45

1 Answers1

1

Communication between threads is a very commong problem and there is a lot of possible solutions.

One solution I see is not using performSelectorInBackground: but instead creating a NSThread instance, save the thread reference and call start. Then you can use one of the [NSObject performSelector:onThread:...] methods to call the stop method (don't forget to actually cancel the request before stopping the loop).

Another solution could be to call CFRunLoopRun with a timeout inside a while cycle, waiting for some condition to happen. See the answer in iPhone: how to use performSelector:onThread:withObject:waitUntilDone: method?.

Another solution is to use local notifications (NSNotificationCenter). The background thread can register itself for notification and the main thread can send them when a condition happens.

Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Suppose I use your first option, then how can I continue that thread? Using one flag and while loop? – Khushbu Shah Apr 24 '13 at 10:13
  • @Mdroid What do you mean by "continue"? The thread will end when you stop it. – Sulthan Apr 24 '13 at 10:56
  • Can you give link or any example of last option (using local notifications). I found [this](http://www.cocoawithlove.com/2009/08/safe-threaded-design-and-inter-thread.html) and [this document](http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Notifications/Articles/Threading.html#//apple_ref/doc/uid/20001289-CEGJFDFG) – Khushbu Shah Apr 25 '13 at 04:23
  • Thank you so much. I have done thread communication using localnotification. – Khushbu Shah Apr 26 '13 at 04:24