2011-09-26 45 views
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; 
} 

回答

1

当然你的主线程使用sendSynchronousRequest:时受阻。如果用户失去互联网连接,这是非常糟糕的做法,用户界面将完全失灵。苹果写在documentation

重要提示:由于此调用有可能需要几分钟 失败(特别是使用iOS的蜂窝网络时),你应该 从来没有从一个主线程调用这个函数GUI应用程序。

我强烈建议使用异步方法connectionWithRequest:delegate:。你可以很容易地捕获到connection:didFailWithError:中的中断。

相信我,这并不难,但非常值得努力。

+0

你能指点一个教程吗?我不熟悉异步方法。 – Baub

+1

看看我的答案[this](http://stackoverflow.com/questions/7420837/how-to-download-docx-pdf-image-pptx-or-any-file-from-a-internet/)问题。这是最短的教程... – Mundi

+0

谢谢!我正在努力实现它。我会回复。 – Baub