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];
}
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.
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!
Related
I'm using NSURLConnection initWithRequest to get some data from a server. This works fine when the server is available. However when the server is not available my app hangs and becomes totally unresponsive for at least 40-50 seconds. I've tried using a timeoutInterval, as well as a timer to cancel the request. However my app still hangs.
Whilst my app is hanging, none of the NSURLConnectionDelegate methods have been called. The onTimeExpire gets called but doesn't do anything. Once the app becomes responsive again (50 seconds later...), the NSURLConnectionDelegate delegate methods get called and all is good...
The server is a local server with ip 192.168.x.x which will pull data down to the app only when the server (and csv) file is available.
I thought of doing a simple check before firing off the NSURLConnection to see if the server is online first. But can't seem to work out how to do this? Any ideas?
-(id) loadCSVByURL:(NSString *)urlString
{
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0f];
self.timer = [NSTimer scheduledTimerWithTimeInterval:20 //for testing..
target:self
selector:#selector(onTimeExpired)
userInfo:nil
repeats:NO];
(void)[self.connection initWithRequest:request delegate:self];
//THE APP HANGS HERE!!!
return self;
}
-(void)onTimeExpired
{
NSLog(#"cancelling connection now!");
[self.connection cancel];
}
You are setting a timeout of 20 but a connection timeout of 30. That means that even if your setup were correct, the timer would fire before the unsuccessful connection fails.
More importantly, you are sending an init message to your connection object twice. This does not make sense.
You need instead to create the connection with the request and then start it.
self.connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];
[connection start];
You then react to the failure of the connection in the NSURLConnectionDelegate callback connection:didFailWithError: which should fire after the connection times out.
I am trying to perform a downloading in a background thread.For this, I have created an instance of NSOperationQueue and add an instance of NSInvocationOperation to it.
operationQueue = [NSOperationQueue new];
// set maximum operations possible
[operationQueue setMaxConcurrentOperationCount:1];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:#selector(startBackgroundThread:)
object:data];
[operationQueue addOperation:operation];
[operation release];
Now in startBackgroundThread,I have created a new NSURLConnection and dispatching the operationQueue to it.
currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if (self.operationQueue) {
[currentConnection setDelegateQueue:self.operationQueue];
}
[currentConnection start];
Behavior in iOS6
Working exactly fine on iOS6.
A thread gets created and NSURLConnection callbacks it delegates on the same background thread.
Behavior in iOS5 and iOS5.1
A thread gets created but NSURLConnection delegates didn't get called.
Am i missing something that need to be taken in account in iOS5?
I have read the documention provided by Apple but nothing is mentioned there related to that.
This is a known issue on iOS 5. See http://openradar.appspot.com/10529053
If you are trying to perform a background web request then use the following convenience method.
[NSURLConnection sendAsynchronousRequest: queue: completionHandler:];
Block apis give better performance and recommended by apple.
I am writing location based app, get weather information through API by using NSURLConnection for current/other places .At first time I sent request its working successfully. But next time I want to refer the information for same place it not working while NSURLConnection is not call the any delegate methods.
this is my code:
NSString *strs=[#"http://www.earthtools.org/timezone-1.1/" stringByAppendingString:[NSString stringWithFormat:#"%#/%#",place.latitude,place.longitude]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:strs]];
self.reqTimeZone=[NSURLConnection connectionWithRequest:request delegate:self];
[self.reqTimeZone start];
I assume you mean NSURLConnection (NSConnection doesn't exist). NSURLConnection can only be used once. See Reusing an instance of NSURLConnection.
Another gotcha with NSURLConnection is that it must be ran on a thread with a runloop. The main thread automatically has a run loop, but methods called on GCD and NSOperation threads need to have the runloop created explicitly. In practice you probably don't need to run NSURLConnection on a background thread. The download operation will not block the main thread. If you do decide to run NSURLConnection on a run loop the easiest way to do it is probably to create an NSOperation subclass and create the run loop inside of -main.
I am running a NSURLConnection on a separate thread (I am aware that it is asynchronous and works when running on the main thread), but it is not making delegate calls even when I pass the parent thread as the delegate. Does anyone know how to do this?
Code:
-(void)startConnectionWithUrlPath:(NSString*)URLpath {
//initiates the download connection - setup
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
//initiates the download connection on a seperate thread
[NSThread detachNewThreadSelector:#selector(startDownloading:) toTarget:self withObject:self];
}
-(void)startDownloading:(id)parentThread {
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[NSURLConnection connectionWithRequest:myURLRequest delegate:parentThread];
//The delegate methods are setup in the rest of the class but they are never getting called...
[pool drain];
}
EDIT*
The reason I need to run NSURLConnection on a separate thread is because I am downloading something in my iPhone app and the download cancels when the user locks the screen (it continues fine if the user simply presses the home button and the app goes into the background). I understand this is due to my running the connection asynchronously on the main thread and not a separate one.
I have also tried this code (NOT in a separate thread) when initiating the NSURLConnection:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
[connection release];
But it I have the same problem with this regarding the download being cancelled on screen lock.
*UPDATE
To add to Thomas' answer below (Please note that James Webster's answer is also correct regarding the exiting of a thread) the Apple docs explain:
"Suspended state - The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code."
Since when the screen is locked by the user the app is put into the background state and than right away into the suspended state, all execution is stopped killing any downloads and no warning that this is about to happen is given... there may be a notification which tells me that the user has locked the screen but I haven't found one yet.
I therefore pause (save certain information and cancel the NSURLConnection) all downloads when the app goes into the background and resume it with the HTTP Range header when it gets active again.
This is a workaround which is ok but not ideal since the download is not occurring in the background which affects the user experience negatively... bummer.
Since your NSURLConnection is asynchronous, the end of your -startDownloading method is reached immediately, and the thread exits.
You should indeed schedule your connection on the main runloop (or use GCD).
The device lock is another issue. When the device is locked, your application is suspended to save battery life. You can probably ask for an extra amount of time when suspending in order to finish your download.
I think your problem might be that the NSURLConnection has been deallocated as soon as you exit the startDownloading: message (or more accurately when your autorelease pool is drained)
However I think your methodology might be a bit uncouth anyway. NSURLConnection the way you are using it is asynchronous and will appear to be threaded anyway.
Try this and see if it works as you expect it to (i.e. your app doesn't pause while your connection is busy)
-(void)startConnectionWithUrlPath:(NSString*)URLpath {
//initiates the download connection - setup
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
[NSURLConnection connectionWithRequest:myURLRequest delegate:self];
}
In the CocoaXMLParser class of Apple's CocoaXMLParser example, the following code appears:
rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[self performSelectorOnMainThread:#selector(downloadStarted) withObject:nil waitUntilDone:NO];
if (rssConnection != nil) {
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} while (!done);
}
According to the NSRunLoop documentation "In general, your application does not need to either create or explicitly manage NSRunLoop objects. Each NSThread object, including the application’s main thread, has an NSRunLoop object automatically created for it as needed." In the context of this, why is the run-loop explicitly managed in this example? Would it not be created and destroyed automatically by the thread generated by the NSURLConnection request?
In that code, the run loop is basically just being told to run forever, so that that thread can continue to process incoming background data from the NSURLConnection. Even though a run-loop is created for you, by default the thread would terminate when that method ended.
In general when doing something like that it's easier to put everything in an NSOperation which then goes in an NSOperationQueue (although if you are implementing NSUrlConnection callbacks you have to provide a few extra methods in the NSOperation class).