2011-09-26 46 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