HTTP帖子连接保证

时间:2011-09-26 21:56:07

标签: objective-c ios cocoa-touch http-post

我有一个使用HTTP POST定期与服务器对话的应用程序。我试图使连接尽可能安全,因此如果没有工作数据连接,应用程序将不会尝试发送一个东西。如何在NSURLConnection中间检测到连接丢失?如果没有最小240的时间,超时不起作用,所以这是不可能的。我可以使用NSTimer,但它仍然挂起,因为NSURLConnection似乎占用主线程不允许任何更改。某种delgate可能吗?

我的代码如下:

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

1 个答案:

答案 0 :(得分:1)

使用sendSynchronousRequest:时,确定您的主要线程被阻止了。这是非常糟糕的做法,如果用户失去互联网连接,UI将完全失灵。 Apple在documentation中写道:

  

重要提示:因为此调用可能需要几分钟时间   失败(特别是在iOS中使用蜂窝网络时),你应该   永远不要从GUI应用程序的主线程调用此函数。

我强烈建议使用异步方法connectionWithRequest:delegate:。您可以轻松捕捉connection:didFailWithError:中的中断。

相信我,这并不难,但值得付出努力。