Asynchronous NSURLConnection on separate thread fails to call delegate methods - iphone

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];
}

Related

NSURLConnection hangs for server which is not available

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.

NSURLRequest delegates not getting called on Device Works fine on simulator.

NSURLRequest delegate methods are not getting called when i run the application on the device. It works perfectly on the simulator though. Also its not the case of my view loading before the request is fulfilled because i enable to view to be loaded only once the connection has received the data.
My code requesting url is here. Any help greatly appreciated.
- (void)viewWillAppear:(BOOL)animated
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://-dev01x/content"]; cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:#"GET"];
_getData = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"HELLO %#",_getData);
}
Your code as provided here makes no sense:
_getData = [[NSURLConnection alloc] initWithRequest:request delegate:self];
That line returns a pointer to a NSURLConnection object, your variable name is misleading. If you want to block at this point (and does that even work) then it would appear you need to use sendSynchronousRequest at that point.
I do something similar to what you want to do, but in a more traditional way. In viewDidLoad or even in the initWithFrame, I will start up an asynchronous connection, set a flag, and set the view backgroundColor to black or white (I use a spinner too normally). When I get viewWillAppear, if the connection has completed, all is well and I set the various UI elements. If not, then don't do anything, and later, when the connection completes, pull down the spinner and update the UI.
The only way I can think of to block the main thread at the point you are trying to would be to use that synchronous request (which IMHO is a really bad way to deal with this).
The beauty of doing things in the background is that if its taking too long, the user can tap the back button or go somewhere else in the app [in which case you cancel the connection and tear everything down.]
Check url u provide to NSMutableURLRequest when checked in browser gives nothing
NSMutableURLRequest needs valid url

send Synchronous request using ASIHTTPREQUEST libraries showing activity indicator in iPhone

I want to show activity indicator while sending and receiving synchronous asihttprequest from server. I have used activity indicator as the asihttprequest is send but it did not showing in iPhone due to synchronous request.Any suggestion how to show activity indicator during synchronous data transfer.Thanks
Synchronous request calls your activity indicator delegate method setProgress: on the main thread.
B/c you are using ASIHTTPRequest on the main thread you are blocking the UI, hence calls to setProgress: are queuing to be dispatched after the request is finished, but by that time the progress is already 100%
To solve this use either asynchronous request or call synchronous request on a background thread using
[self performSelectorInBackground:#selector(startSynchronous:) withObject:nil];
Edit
Remember to create your own autorelease pool to handle the memory inside your startSynchronous: method
-(void)startSynchronous:(BOOL)animate{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *autoreleasedString = #"xxx";
NSLog(#"%#",autoreleasedString);
[pool drain];
}

NSURLConnection and NSTIMER issue

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!

how to apply the backgroud process in my iPad application without effecting the process running on foreground?

I'm Developing an iPad application where I need to download file from the Webservice and I don't want it affect any other process running on the foreground.
I am displaying the data from the local database in my app and also this data is coming from the web service.
Help Is Appreciated.
Thank You Very Much in advance.
NSURLConnection and its delegate method will allow an asynchronous(background thread) load of a URL request.
Refer the NSURLConnection Class Reference
After getting the data from the server you should parse it on another secondary thread. Then you can save it to the Database.
You can find a better demonstration in the Apple sample apps. Please check the TopPaid app .
This sample app don't have a Database management module. But will teach you to develop a Universal (iPad and iPhone compatible app).
Few thoughts:
you can run the download process on separate thread.
Write a class as below
#interface FileDownloader : NSOperation
//with following methods:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:fileRecord.fileURLString]] delegate:self startImmediately:YES];
you can use thread use below method to detach thread
[NSThread detachNewThreadSelector:#selector(yourMethod) toTarget:self withObject:nil];
now perform your task in method
-(void) yourMethod {
//ur work
}
good luck
When downloading from a service in the background, I prefer to use synchronous calls running on a separate thread. This is how I do it in most of my apps.
call my generic method that spins a new thread
[[MyServiceSingleton sharedInstance] doSomeWorkInBackground:param1];
within singleton - define private method - doSomeWorkBackgroundJob (I use the empty category approach) to call within doSomeWorkInBackground method
[self performSelectorInBackground:#selector(doSomeWorkBackgroundJob:) withObject:param1];
within background job - create pool, do work, drain pool
- (void)doSomeWorkBackgroundJob:(NSString *)param1 {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
assert(pool != nil);
// you can call another method here or just create your synchronous request and handle the response data
[pool drain];
}