2010-06-07 75 views
0

我有一個簡單的表格界面設置一個發送用戶名和密碼信息發送到服務器:(工作)妥善處理NSURLConnection的錯誤

NSString *postData = [NSString stringWithFormat:@"user=%@&pass=%@",[self urlEncodeValue:sysUsername],[self urlEncodeValue:password]]; 
NSLog(@"Post data -> %@", postData); 
/// 
NSData* postVariables = [postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease]; 
NSString* postLength = [NSString stringWithFormat:@"%d", [postVariables length]]; 
NSURL* postUrl = [NSURL URLWithString:@"http://localhost/~csmith/cocoa/test.php"]; 
[request setURL:postUrl]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody: postVariables]; 

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL]; 
NSLog(@"Post data SENT & returned -> %@", returnData); 

如何處理連接錯誤,如沒有互聯網連接,防火牆等 此外,此方法是否使用系統範圍的代理設置?我的許多用戶都在代理之後。

非常感謝!

回答

1

首先,您不應該使用同步請求,而是使用異步請求,並使用indeterminate progress indicators指示活動。

當使用異步請求,你必須設置一個委託實施delegate methods,值得注意的是:

從文檔:

除非NSURLConnection的接收到取消消息,代表將r只有一個connectionDidFinishLoading:connection:didFailWithError:消息,但從來沒有。另外,一旦發送任何一條消息,代理將不會收到給定NSURLConnection的更多消息。

至於最後一個問題:

此外,沒有這種方法使用系統範圍的代理設置?

是的,NSURLConnection自動使用它們。

1

您應該使用異步請求來處理代理和網絡錯誤。這樣更有效率。 要添加額外的檢查,您可以在通信之前在代碼中添加可達性測試。你可以找到伸手能力測試代碼here