【问题标题】:NSMutableURLRequest setTimeoutInterval issueNSMutableURLRequest setTimeoutInterval 问题
【发布时间】:2011-11-17 18:43:08
【问题描述】:

首先,如果我如下使用 NSURLReuqest(non mutable),则连接会根据设置的内容超时。 奇怪的是为什么 NSLog 总是读 0?

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 秒左右超时。甚至比默认的 60 秒还要长...

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

我试过了

self.requestURL = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0] autorelease];

【问题讨论】:

    标签: iphone nsmutableurlrequest


    【解决方案1】:

    试试这个

    NSLog(@"request timeOutInterval:%f", self.requestURL.timeoutInterval);它对我有用。

    更新

    在之前的SO question中查看@Francois 的答案

    Apple 开发者论坛上有一个讨论这个问题的帖子。显然 在 iPhone OS 上,setter 要求 timeoutInterval 至少为 240 秒(4 分钟)。这仅在 postBody 不为空时发生 (通常在使用 POST 请求时)。这看起来很疯狂,但是 显然它的存在是为了确保请求甚至离开系统 尽管唤醒 WWAN (3G) 接口可能需要几秒钟 向上。 240 秒似乎相当陡峭,所以他们建议设置一个计时器并 定时器触发时取消异步连接。我知道这个 似乎很愚蠢,但这是我唯一设法让 POST 超时 请求...

    【讨论】:

    • 我明白了,我使用的是 POST 方法。但它在 75 秒而不是规定的 240 时超时。我想知道苹果为什么要强制执行...
    • 不确定。但我更喜欢 ASIHTTPRequest。它好多了。
    【解决方案2】:

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

    尝试改用%f,这表示您要记录一个双精度值。

    【讨论】:

    • @好的,两个 NSLogs 现在都读取 20.0000。但真正的问题是为什么我的 NSMutableURLRequest 在达到 timeoutInterval(20s) 时没有触发 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 委托回调方法。相反,它仅在 75 秒左右超时。甚至比默认的 60 秒还要长...
    【解决方案3】:

    它对我有用:

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

    【讨论】:

      【解决方案4】:

      使用%fNSTimeInterval 是浮点数。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-05
        • 2013-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多