我正在开发一个 iOS 应用程序,它使用 NSMutableURLRequest
和 NSURLConnection
将数据发送到我的服务器。我需要在失败时显示错误消息。我发送请求的代码如下所示
const int TIMEOUT = 120;
-(void)send:(id<NSURLConnectionDelegate>)delegate
{
bodyContents = [bodyContents stringByAppendingFormat:@"--%@--",boundry];
NSData *data = [bodyContents dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[request setValue:[NSString stringWithFormat:@"%i",[data length]+4] forHTTPHeaderField:@"Content-Length"];
NSLog(@"Timeout before setting custom is %f",request.timeoutInterval);
[request setTimeoutInterval:TIMEOUT];
NSLog(@"Timeout after setting custom is %f",request.timeoutInterval);
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:delegate];
if(connection)
NSLog(@"Connection good");
else
NSLog(@"Connection not so good");
}
//in the delegate class
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(@"connectionDidFinishLoading");
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
{
NSLog(@"Failed with error %@",error);
btnCancel.title = @"Retry";
self.navigationItem.hidesBackButton = NO;
[self showAlertDialog:[NSString stringWithFormat:@"%@",[error localizedDescription]] :@"Error"];
}
我希望在 2 分钟无响应后调用 didFailWithError 消息。相反,它会在大约 15 秒无响应后被调用,这没有任何意义。我查看了文档以检查我是否错误地设置了超时,我唯一能找到的是带有正文的帖子的最短超时是 240 秒,我不情愿地接受了这一点。
运行应用程序的输出如下所示:
2012-06-22 16:49:12.393 Media Upload[672:707] Timeout before setting custom is 240.000000
2012-06-22 16:49:12.394 Media Upload[672:707] Timeout after setting custom is 240.000000
2012-06-22 16:49:12.395 Media Upload[672:707] Connection good
2012-06-22 16:49:29.174 Media Upload[672:707] Failed with error Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." etc
我很困惑为什么超时这么快。创建连接时服务器未启动,所以我什至不确定为什么它说连接好而不是连接不太好,但这是一个不同的问题(我希望)有什么建议吗?
最佳答案
所以,我怀疑答案全在语义上。
至于“连接良好”而不是“连接不太好”的日志记录,这是因为初始化连接不会等待它在网络上做任何。它确实使它立即启动,但不会在它从 init 方法返回之前启动。
更有趣的(阅读:误导)问题是超时。我怀疑超时设置的真正含义是,“如果我已经建立了连接,但服务器还没有给我响应字节”。这与“我一直在尝试,但无法连接”不同。当你这样想时,它有一定的道理;一个超时值仅用于所有“网络”内容(路由和握手),另一个用于要处理的实际有效负载。
关于iphone - NSMutableURLRequest 在大约 15 秒后超时。超时设置为 240 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11165197/