我有一种方法可以创建NSURLRequest
,并用NSURLConnection
方法sendAsynchronousRequest:queue:compltionHandler:
发送该请求。这在我获取json文件或图像数据时工作正常,但是当我尝试读取XML文档时,发生了一些非常奇怪的事情。该方法正在被调用,但从来没有响应,所以完成处理程序永远不会被调用。有谁知道如何解决这一问题?我已经使用了这种方法数百次,但我从未见过这种行为。这里就是我所说的sendAsynchronousRequest:queue:compltionHandler:
NSURLConnection sendAsynchronousRequest没有得到响应
- (void)getCachedFile:(NSString *)title withCompletion:(void (^)(NSData *data))completion
{
Reachability *reach = [Reachability reachabilityForInternetConnection];
NetworkStatus status = [reach currentReachabilityStatus];
if (status == NotReachable)
{
// read data locally
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:[self filePath:title]
options:NSDataReadingUncached
error:&error];
if (error)
{
NSLog(@"COULD NOT READ LOCAL CACHED DATA: %@", error.localizedDescription);
}
else
{
completion(data);
}
}
else
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:title]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0f];
// get data from NSURLCache
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse)
{
// if the data is found in the response, use it
completion([cachedResponse data]);
}
else
{
// get the data from the server
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError)
{
NSLog(@"ERROR CONNECTING DATA FROM SERVER: %@", connectionError.localizedDescription);
}
else
{
[self.writingOperationQueue addOperationWithBlock:^{
[[NSFileManager defaultManager] createFileAtPath:[self filePath:title]
contents:data
attributes:nil];
}];
completion(data);
}
}];
}
}
}
这样的作品,感谢您的帮助! –
我普遍同意,但有两个非常小的观察:1.在完成块中包含'self'不会在这种情况下引起强烈的参考周期。它只是在网络运营期间保留“自我”。 2.'sendAsynchronousRequest'中的'queue'不是网络操作发生的地方,而是运行完成块的地方。鉴于他正在保存'writingOperationQueue'(这很好),他可能只是使用'[NSOperationQueue mainQueue]'这样'complete'模块在主队列上运行(这对于UI和模型更新可能很重要)。 – Rob
在这种情况下,您可以接受这些更改,但不是在任何情况下。我想确保它可以被广泛应用,即使在其他用户滥用它时也是如此。 – Holly