NSMutableURLRequest timeout interval 不起作用的原因

在WWAN连接中使用NSURLRequest进行POST请求时,设置的timeoutInterval会被系统默认更改为240秒,这可能是为了防止因网络不稳定导致的连接异常。本文提供了三种解决方案:改用GET请求、后台另开线程处理或使用NSTimer进行自定义超时控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.sina.com.cn/s/blog_67a5e4720100yz4a.html

 

 

先看一段测试代码:

 

 
  1. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theURL]

  2. cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData

  3. timeoutInterval:10.0];

  4. [request setHTTPMethod:theMethod];

  5.  
  6. // Ok here

  7. NSLOG(@"timeout: %f", request.timeoutInterval); // Displays 10.000000

  8.  
  9. NSString *fullRequestString = @"name=name&value=value"; // not real data

  10. [request setHTTPBody: [fullRequestString dataUsingEncoding:NSASCIIStringEncoding]];

  11.  
  12. // Timeout changed here, no idea why

  13. NSLOG(@"timeout: %f", request.timeoutInterval); // Displays 240.000000

  14. [request setTimeoutInterval:10.0];

  15.  
  16. NSLOG(@"timeout: %f", request.timeoutInterval); // Displays 240.000000

 

 

利用POST方式进行URLConnection,在WWAN连接情况下,在设置了setHTTPBody之后,系统会默认修改timeoutInterval为240s,可能是因为在WWAN(连wifi测试后也一样...)连接时,一个太短的timeout可能会引起一些不必要的问题,所以apple强制把有body信息的post连接的timeout设定为240s。

 

想要修改时间三种方式:

1. 改为get方式,如果可以的话。

         可以参考前一篇post和get方式连接网络的文章

2. 放在后台另开一条线程运行。

3. 利用NSTimer,写一个计时器,时间到cancel掉connection。

    计时器程序如下,

 
 
  1. if (needsSeparateTimeout){

  2.  
  3. SEL sel = @selector(customCancel);

  4.  
  5. NSMethodSignature* sig = [self methodSignatureForSelector:sel];

  6.  
  7. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:sig];

  8.  
  9. [invocation setTarget:self];

  10.  
  11. [invocation setSelector:sel];

  12.  
  13. NSTimer *timer = [NSTimer timerWithTimeInterval:WS_REQUEST_TIMEOUT_INTERVAL invocation:invocation repeats:NO];

  14.  
  15. [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

  16.  
  17. }

  18. In the custom cancel method the connection is cancelled

  19.  
  20. [super cancel];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值