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