我正在使用ASIHTTPRequest库从我的iPhone应用程序中的服务器请求一些数据。但我无法弄清楚如何创建超时,以便如果服务器出现故障或iPhone没有互联网连接,应用程序不会崩溃。
提前致谢
编辑>>>
tt.Kilew你的代码不起作用......我发布了一些示例代码
NSURL *url = [NSURL URLWithString:@"A URL WITH A FORM"];
ASIFormDataRequest *requestPOST = [ASIFormDataRequest requestWithURL:url];
[requestPOST setPostValue:un forKey:@"username"];
[requestPOST setPostValue:pw forKey:@"password"];
[requestPOST setPostValue:@"Login" forKey:@"submit"];
[requestPOST start];
[requestPOST setTimeOutSeconds:10];
NSLog(@"Fail: %@", [requestPOST failWithError:ASIRequestTimedOutError]);
答案 0 :(得分:16)
[request setTimeOutSeconds:10];
使用更多代码进行更新:
NSURL *url = [NSURL URLWithString:@"A URL WITH A FORM"];
ASIFormDataRequest *requestPOST = [ASIFormDataRequest requestWithURL:url];
[requestPOST setPostValue:un forKey:@"username"];
[requestPOST setPostValue:pw forKey:@"password"];
[requestPOST setPostValue:@"Login" forKey:@"submit"];
[requestPOST setTimeOutSeconds:10];
[requestPOST setDelegate:self]
[requestPOST startAsynchronous];
处理程序失败:
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
if ([error isKindOfClass:[ASIRequestTimedOutError class]]) {
// Actions specific to timeout
}
}
成功处理程序:
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
// Do something with the response.
}
答案 1 :(得分:8)
我通常会这样检查:
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSString *message = NULL;
NSError *error = [request error];
switch ([error code])
{
case ASIRequestTimedOutErrorType:
message = kAlertMsgTimeoutError;
break;
case ASIConnectionFailureErrorType:
message = kAlertMsgConnectionFailError;
break;
case ASIAuthenticationErrorType:
message = kAlertMsgAuthFailError;
break;
case ASITooMuchRedirectionErrorType:
message = kAlertMsgTooManyRedirect;
break;
case ASIRequestCancelledErrorType:
message = kAlertMsgReqCancelledError;
break;
case ASIUnableToCreateRequestErrorType:
message = kAlertMsgUnableCreateReqError;
break;
case ASIInternalErrorWhileBuildingRequestType:
message = kAlertMsgUnableBuildReqError;
break;
case ASIInternalErrorWhileApplyingCredentialsType:
message = kAlertMsgUnableApplyCredError;
break;
case ASIFileManagementError:
message = kAlertMsgFileManageError;
break;
case ASIUnhandledExceptionError:
message = kAlertMsgUnhandledExcepError;
break;
case ASICompressionError:
message = kAlertMsgCompressionError;
break;
default:
message = kAlertMsgGenericError;
break;
}
if (NULL != message)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kApplicationTitle
message:message
delegate:self
cancelButtonTitle:kAlertDefaultCancel
otherButtonTitles:nil];
[alert show];
}
}
答案 2 :(得分:0)
// Number of seconds to wait before timing out - default is 10
NSTimeInterval timeOutSeconds;
如果超时,你会收到
[self failWithError:ASIRequestTimedOutError];