我认为我已经编辑了这篇文章以使其更易于阅读。
在 dispatch_async 块中完成一些密集的字符串操作后,我需要调用 NSUrlConnection。
我调用的 URL 有 .htaccess 身份验证,所以我不能使用同步连接。
但是没有调用 NSURLConnection 委托方法。我知道 URL 在浏览器中大约 5 秒后加载,并且我已经使用没有身份验证的简单 URL 测试了代码,它没有任何区别。
是什么阻止了委托方法被调用?
这个函数做了一些字符串操作,需要一段时间才能完成:
- (void)performSearch {
// set some defaults and work out if it is a valid search, setting bSearchOk
if (bSearchOk) {
// update some interface elements
self.msgBox.text = @"Translating...";
self.plateInput.enabled = NO;
self.searchProgress.hidden = NO;
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// create a new search
Search *oPlateSearch = [[Search alloc] initWithTerm:thisTerm];
// ...
// perform search... this calls a variety of slow and intensive functions
// ...
self.aFinalPlates = [oPlateSearch.aValidated copy];
self.aCurrentPlates = [oPlateSearch.aFinals copy];
dispatch_async( dispatch_get_main_queue(), ^{
[oPlateSearch release];
// make ajax call to check if plates can be bought
[self getPrices];
});
});
} else {
// hide results
self.searchResults.hidden = YES;
}
}
这是在上面的块末尾调用的那个
/* call to get plate availability and prices */
-(void) getPrices {
// set return message
self.msgBox.text = @"Getting prices and availability";
// ...
// then I build my strRequest var, which is a valid working URL
// ...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strRequest]];
NSURLConnection *loginConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSLog('This will get logged');
if(loginConnection) {
NSLog('This will also get logged');
self.jsonSearchResponse = [[[NSMutableData data] retain] autorelease];
NSLog('And this will get logged, so it's not throwing errors');
} else {
NSLog(@"Failed to get search results");
}
}
更新:我也试过这个,因为它在另一个类似问题的答案中被接受,但它没有奏效:
NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[loginConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[loginConnection start];
基于这个问题:Why NSURLConnection delegate methods don't get call, when using the global dispatch queue?