gpt4 book ai didi

iphone - NSURLConnection 验证

转载 作者:行者123 更新时间:2023-12-03 20:24:11 26 4
gpt4 key购买 nike

我正在尝试验证连接是否成功,但得到的结果不稳定。当我尝试使用虚假网址执行同步请求时:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (responseData)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}

它挂起一段时间,最终返回:

 did_send = FALSE;

但是如果我使用虚假网址执行异步请求:

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self ];
if (conn)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}

我得到:

did_send = TRUE;

每次。我需要让异步请求正常工作,因为我能够设置超时,而不必在请求超时且默认超时持续时间(异步请求无法更改)时挂起 60 秒。有什么想法吗?

最佳答案

尝试使用 nsurlconnection 类委托(delegate)方法 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];

}

关于iphone - NSURLConnection 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3496245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com