我正在尝试验证连接是否成功,但得到的结果不稳定。当我尝试使用伪造的url执行同步请求时:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}它挂起了一段时间,并最终返回:
did_send = FALSE;但是如果我使用一个伪造的url进行异步请求:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self ];
if (conn)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}我得到了:
did_send = TRUE;每次都是这样。我需要让异步请求工作,因为我能够设置超时,并且在请求超时时不需要挂起60秒,而默认的超时持续时间对于异步请求是不可更改的。有什么想法吗?
发布于 2010-08-17 02:55:09
尝试使用nsurlconnection类的委托方法connection:didFailWithError:,这样可以得到一致的结果。
-(void)getLocationsFromWebService {
NSLog(@"in getLocationsFromWebService");
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:self.locationsURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
self.requestType = @"GET";
if (theConnection) {
_responseData = [[NSMutableData data] retain ];
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
NSLog(@"in mapviewcontroller");
NSLog(@"Error connecting - %@",[error localizedDescription]);
[connection release];
[_responseData release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = [HTTPResponse statusCode];
if (404 == statusCode || 500 == statusCode) {
//[self.controller setTitle:@"Error Getting Parking Spot ....."];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
[connection cancel];
NSLog(@"Server Error - %@", [NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
} else {
if ([self.requestType isEqualToString:@"GET"])
[_responseData setLength:0];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if ([self.requestType isEqualToString:@"GET"])
[_responseData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
if ([self.requestType isEqualToString:@"GET"]) {
[self parseLocations:_responseData];
[_responseData release];
}
[connection release];
}发布于 2010-08-17 05:02:39
简单地实例化NSURLConnection不会做任何事情。它创建该类的一个实例,但不开始数据传输--即使请求不可能得到满足,对象通常也是非空的。
相反,委托对象(代码中的self)需要实现NSURLConnectionDelegate (它将处理诸如“传入数据”或“错误条件”之类的回调)。然后,您必须向NSURLConnection实例发送-start消息,该消息将在正在执行的线程的run循环中调度它。
有关NSURLConnectionDelegate协议的更多信息(包括如何在回调中执行的信息),请参阅苹果的“URL Loading System Programming Guide”。
https://stackoverflow.com/questions/3496245
复制相似问题