Objective c HTTP后连接保证
我有一个应用程序,它定期使用HTTPPOST与服务器通信。我正试图使连接尽可能的故障安全,这样应用程序将不会试图发送一个东西,如果它没有一个工作的数据连接。如何在Objective c HTTP后连接保证,objective-c,ios,cocoa-touch,http-post,Objective C,Ios,Cocoa Touch,Http Post,我有一个应用程序,它定期使用HTTPPOST与服务器通信。我正试图使连接尽可能的故障安全,这样应用程序将不会试图发送一个东西,如果它没有一个工作的数据连接。如何在NSURLConnection过程中检测连接丢失?如果没有240的最短时间,超时将不起作用,因此这是不可能的。我可以使用NSTimer,但它仍然挂起,因为NSURLConnection似乎占用了主线程,不允许任何更改。也许是某种德尔盖特 我的代码如下: -(NSData*) postData: (NSString*) strData /
NSURLConnection
过程中检测连接丢失?如果没有240的最短时间,超时将不起作用,因此这是不可能的。我可以使用NSTimer
,但它仍然挂起,因为NSURLConnection
似乎占用了主线程,不允许任何更改。也许是某种德尔盖特
我的代码如下:
-(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;
}
使用
sendSynchronousRequest:
时,确保主线程被阻止。这是非常糟糕的做法,因为如果用户失去互联网连接,用户界面将完全失灵。苹果在文章中写道:
重要提示:因为此呼叫可能需要几分钟才能完成
失败(特别是在iOS中使用蜂窝网络时),您应该
切勿从GUI应用程序的主线程调用此函数。
我强烈建议使用异步方法connectionWithRequest:delegate:
。您可以在连接:didFailWithError:
中轻松捕获中断
相信我,这并不难,但很值得付出努力。你能指出一些教程吗?我不熟悉异步方法。请查看我对问题的回答。这是最短的教程。。。