1

I am currently trying to have a time out of 20 second when making an async request.

The issue am having is that the NSURLconnection runs on the main thread and therefore, if I run an NSTIMER to count the number of seconds that has passed, it never fires the selector since the NSURLconnection is blocking the main thread. I can probably run the NSURLconnection on a different thread since it is thread safe but I have weird issues with my delegates not being called etc.. any help is appreciated.

Below is my sniplet:

    NSURL *requestURL = [NSURL URLWithString:SERVER];
    NSMutableURLRequest *req = [[[NSMutableURLRequest alloc] initWithURL:requestURL] autorelease];
    theConnection = [[NSURLConnection alloc]initWithRequest:req delegate:self];


if (!timeoutTimer) {
    NSLog(@"Create timer");
    timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUT target:self selector:@selector(cancelURLConnection) userInfo:nil repeats:YES];

}
user281300
  • 1,427
  • 2
  • 19
  • 31

2 Answers2

2

The asynchronous methods of NSURLConnection do not block the main thread. If your timer isn't firing, this has other reasons. Your problems with using it on a background thread result from the fact that a background thread doesn't have a runloop by default.

omz
  • 53,243
  • 5
  • 129
  • 141
  • Thanks. You are actually right. The asynchronous request should not be blocking the main thread. Hmm I am basically creating a connection and then creating a timer. – user281300 Aug 10 '11 at 23:38
  • 1
    Have you considered using the `setTimeoutInterval:` method of `NSMutableURLRequest` instead of creating your own timer? – omz Aug 10 '11 at 23:46
  • I tried removing it and hardcoding it, the selector never gets called. – user281300 Aug 10 '11 at 23:50
  • Looks like there is a solution here: http://stackoverflow.com/questions/1466389/nsmutableurlrequest-timeout-interval-not-taken-into-consideration-for-post-reques – user281300 Aug 10 '11 at 23:54
  • Found out the issue, stupid me had a lingering invalidate method at the bottom :) – user281300 Aug 11 '11 at 00:04
0

This is a great tutorial on how to set up a simple NSOperation to run a method on a separate thread. I'd start with this based on what you have mentioned. Hope that helps!

msgambel
  • 7,320
  • 4
  • 46
  • 62