I have an application that speaks to a server on a regular basis using HTTP POST. I am trying to make the connection as failsafe as possible, so the application will not try to send a thing if it does not have a working data connection. How can I detect a connection loss du开发者_如何学Cring the middle of a NSURLConnection
? The timeout does not work without a minimum time of 240, so that is out of the question. I could use an NSTimer
, but it still hangs because the NSURLConnection
seems to take up the main thread not allowing any changes. Some sort of delgate maybe?
My code is as follows:
-(NSData*) postData: (NSString*) strData //it's gotta know what to post, nawmean?
{
//postString is the STRING TO BE POSTED
NSString *postString;
//this is the string to send
postString = @"data=";
postString = [postString stringByAppendingString:strData];
NSURL *url = [NSURL URLWithString:@"MYSERVERURLHERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];
//setting prarameters of the POST connection
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//[request setTimeoutInterval:10.0];
NSLog(@"%@",postString);
NSURLResponse *response;
NSError *error;
NSLog(@"Starting the send!");
//this sends the information away. everybody wave!
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Just finished receiving!");
if (urlData == nil)
{
if (&error)
{
NSLog(@"ERROR");
NSString *errorString = [NSString stringWithFormat:@"ERROR"];
urlData = [errorString dataUsingEncoding:NSUTF8StringEncoding];
}
}
return urlData;
}
Sure your main thread is blocked when using sendSynchronousRequest:
. That is very bad practice for if the user loses the internet connection, the UI will be completely out of order. Apple writes in the documentation:
Important: Because this call can potentially take several minutes to fail (particularly when using a cellular network in iOS), you should never call this function from the main thread of a GUI application.
I strongly advise to use the asynchronous methods connectionWithRequest:delegate:
. You can easily catch the interruption in connection:didFailWithError:
.
Believe me, it's not that hard, but well worth the effort.
精彩评论