0
我有一个应用程序,使用HTTP POST定期与服务器通话。我正在尝试使连接尽可能失效,所以如果应用程序没有可用的数据连接,它将不会尝试发送一个事件。如何在NSURLConnection
中检测到连接丢失?没有240的最小时间,超时不起作用,所以这是不可能的。我可以使用NSTimer
,但它仍然挂起,因为NSURLConnection
似乎占用了不允许任何更改的主线程。某种类型的delgate可能?HTTP邮件连接保证
我的代码如下:
-(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;
}
你能指点一个教程吗?我不熟悉异步方法。 – Baub
看看我的答案[this](http://stackoverflow.com/questions/7420837/how-to-download-docx-pdf-image-pptx-or-any-file-from-a-internet/)问题。这是最短的教程... – Mundi
谢谢!我正在努力实现它。我会回复。 – Baub