NSMutableURLRequest timeout interval 不起作用的原因

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];

猜你喜欢

转载自blog.csdn.net/georgehenrywilliam/article/details/88123001
今日推荐