当前位置:编程学习 > wap >>

iphone之解决NSURLConnection timeout失效问题

NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:self.address                                                                       cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                                          timeoutInterval:self.defaultTimeout];

timeoutInterval  已经没有了作用。

这个问题只有在3.0以及之后的os中才有的,而且只有在当调用了setHTTPBody之后才会出现timeout失效。这个是苹果公司对URLLoadingSystem的在OS3.0中的一个改动,不过在我看来其实这就是一个bug!在setHTTPBody之后,request的timeout会被改为240s(这个你可以通过NSLog [requesttimeoutInterval]查看),苹果开发人员的解释就是通常我们自己设置的太短的timeout其实是没什么作用的,尤其对移动设备上来讲与网络沟通需要的时间往往是比较长的,假如你的timeout是10s,在WWAN的网络环境下,可能才刚刚“bring WWANInte易做图ce up”(不知道怎么翻译,囧)。所以自从OS 3后,如果设置了HTTPbody的data,系统就会自动设置一个最低的timeout值,即240s,而且这个值都是不能被改动的,即是你自己再次设置了timeoutInterval,你通过NSLog [request timeoutInterval]得到的还是240S!!


我想的解决办法只有自定义一个操作。办法比较笨,但是真的好使

   NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:self.address
                                                                                     cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                                               timeoutInterval:self.defaultTimeout];
    NSData*bodyData = [outputBodydataUsingEncoding:NSUTF8StringEncoding];
  
    if(cookies!= nil) {
       [requestsetAllHTTPHeaderFields:[NSHTTPCookierequestHeaderFieldsWithCookies:cookies]];
    }
    [requestsetValue:@"wsdl2objc" forHTTPHeaderField:@"User-Agent"];
    [requestsetValue:soapAction forHTTPHeaderField:@"SOAPAction"];
    [requestsetValue:@"text/xml; charset=utf-8"forHTTPHeaderField:@"Content-Type"];
    [requestsetValue:[NSString stringWithFormat:@"%u", [bodyData length]]forHTTPHeaderField:@"Content-Length"];
    [requestsetValue:self.address.host forHTTPHeaderField:@"Host"];
    [requestsetHTTPMethod: @"POST"];

    [requestsetHTTPBody: bodyData];
     
   NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:operation];
  
    //自定义时间超时
    [NSTimerscheduledTimerWithTimeInterval:self.defaultTimeout target: selfselector: @selector(handleTimer) userInfo:operationrepeats:NO];
  
   operation.urlConnection = connection;
  
    [connectionrelease];
}

//时间超时定义
-(void) handleTimer
{
   [operationCopy connection:[NSError errorWithDomain:@"时间超时!"code:256 userInfo:nil]];
}


摘自 进阶码农的专栏
补充:移动开发 , IOS ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,