2011-09-15 50 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);