NSMutableURLRequest timeout interval 不起作用的原因

先看一段测试代码:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theURL]
                       cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                         timeoutInterval:10.0];
[request setHTTPMethod:theMethod];

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

NSString *fullRequestString = @"name=name&value=value";  // not real data
[request setHTTPBody: [fullRequestString dataUsingEncoding:NSASCIIStringEncoding]];

// Timeout changed here, no idea why
NSLOG(@"timeout: %f", request.timeoutInterval);   // Displays 240.000000
[request setTimeoutInterval:10.0];

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。
      计时器程序如下,
if (needsSeparateTimeout){

    SEL sel = @selector(customCancel);

    NSMethodSignature* sig = [self methodSignatureForSelector:sel];

    NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:sig];

    [invocation setTarget:self];

    [invocation setSelector:sel];

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

    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

}
In the custom cancel method the connection is cancelled

[super cancel];


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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值