2011-09-15 47 views
1

好吧,首先,如果我使用NSURLReuqest(不可变),如下所示,连接会根据设置的内容做相应的超时。 奇怪的是为什么NSLog总是读0?NSMutableURLRequest setTimeoutInterval问题

self.requestURL = [NSURLRequest requestWithURL:[NSURL URLWithString:requestString]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0]; 
NSLog(@"request timeOutInterval:%d", self.requestURL.timeoutInterval); // always 0 

接下来,我做了这样的事情,timeoutInterval没有设置。

self.requestURL = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestString]] autorelease]; 
[self.requestURL setTimeoutInterval:20]; 
NSLog(@"request timeOutInterval:%i", self.requestURL.timeoutInterval); // same thing always 0 here. 

编辑。我现在使用%f来记录timeoutInterval属性,并且都读取20.000。但真正的问题是,为什么我的NSMutableURLRequest在到达timeoutInterval(20s)时没有触发- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error委托回调方法。相反,它只是在大约75年代才会超时。甚至比60s的默认时间更长...

即使我删除了[self.requestURL setTimeoutInterval:20];行,连接仍然在75秒超时。

我已经试过

​​

回答

3

试试这个

NSLog(@"request timeOutInterval:%f", self.requestURL.timeoutInterval);它为我工作。

UPDATE

入住此答案由@Francois在此以前SO question

There's a thread on Apple dev forums discussing this issue. Apparently on iPhone OS, the setter mandates timeoutInterval a minimum of 240 seconds (4 minutes). This only occurs when the postBody is not empty (typically when using a POST request). This seems crazy, but apparently it's there to make sure requests leave the system even though it might take many seconds for the WWAN (3G) interface to wake up. 240 seconds seems rather steep, so they suggest to set a timer and cancel the asynchronous connection when your timer fires. I know this seems stupid, but that's the only I managed to get timeout for POST requests...

+0

我看到,我使用POST方法。但它超过了75s而不是240。我想知道为什么苹果强制执行这个... –

+0

不确定。但我更喜欢ASIHTTPRequest。它好多了。 – visakh7

0

NSLog语句使用%d格式说明,它表示一个整数,但timeoutInterval属性是一个双。

尝试使用%f代替,这表示您想记录一个双精度值。

+0

@Ok,既NSLogs现在读20.0000。但真正的问题是为什么我的NSMutableURLRequest不会触发' - (void)连接:(NSURLConnection *)连接didFailWithError:(NSError *)错误{}当委托回调方法达到timeoutInterval(20s)时。相反,它只是在大约75年代才会超时。更长的时间,然后60秒的默认值... –

0

使用%f,NSTimeInterval是浮点数。

Refer Foundation data types ref: 
NSTimeInterval 
Used to specify a time interval, in seconds. 
typedef double NSTimeInterval; 
0

它为我工作:

NSLog(@"request timeOutInterval:%@", requestURL.timeoutInterval);