我一直在摸不着头脑,试图弄清楚为什么 NSURLConnection 没有向我的班级调用它的委托方法。该方法在 99.999% 的情况下都可以正常工作,但偶尔会创建 NSURLConnection,然后不会回调。我已经检查了带有调试信息的线程,以确保它在主线程上执行(这个函数只能通过按下总是在主线程上的 UI 元素来调用)。我当时还检查了连接数,有好几次都是 1,所以我不能达到任何形式的最大连接数。此调用使用的 URL 每次都是相同的,因此我排除了不正确的 URL,因为它在大多数情况下都有效
下面的代码显示了调用的函数:
- (void) getProperties:(NSString *) userID propertyFlag:(PropertyFlag)propertyFlag delegate:(id) target setState:(id) state
{
if(!userID)
{
NSException *anException = [[NSException alloc] initWithName:NSInvalidArgumentException reason:@"userId is equal to nil" userInfo:nil];
[anException raise];
}
NSDictionary *userState = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:target, state, self, FUNCTION_NAME, nil]
forKeys:[NSArray arrayWithObjects:@"callback", @"state", @"_self", @"request", nil]];
// Create the connection state handler and set the delegates and type
ConnectionStateHandler *connectionStateHandler = [[ConnectionStateHandler alloc] init];
connectionStateHandler.delegate = self;
connectionStateHandler.state = userState;
// create the target URL
NSString *targetURL = [NSString stringWithFormat:@"someurl"];
NSURL *url = [NSURL URLWithString:targetURL];
DLog(@"getProperties:propertyFlag:delegate:setState - url: %@", targetURL);
DLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));
// create the request
NSMutableURLRequest *request = [PSMNSURLRequestBuilder createRequestWithURL:url];
connectionStateHandler.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:connectionStateHandler] autorelease];
}
我已经实现了所有必需的委托方法,并且如前所述,它可以正常工作。如果有人可以就线程、连接计数和错误的 URL 以外的问题给我任何想法,我将不胜感激!
提前感谢任何评论者
编辑:
我在 ConnectionStateHandler 对象中实现了以下委托方法(这些方法中的每一个都有登录以显示它们何时被调用,但是在极少数情况下它们不会被调用):
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (NSURLRequest *)connection: (NSURLConnection *)inConnection willSendRequest:(NSURLRequest *)inRequest redirectResponse: (NSURLResponse *)inRedirectResponse;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection