【发布时间】:2014-01-28 22:30:26
【问题描述】:
我有一个创建NSURLRequest 的方法,并使用NSURLConnection 方法sendAsynchronousRequest:queue:compltionHandler: 发送该请求。这在我获取 json 文件或图像数据时工作正常,但是当我尝试获取 XML 文档时,发生了一些非常奇怪的事情。该方法正在被调用,但从来没有响应,所以完成处理程序永远不会被调用。有谁知道如何解决这一问题?我已经使用这种方法数百次了,但我从未见过这种行为。这是我调用sendAsynchronousRequest:queue:compltionHandler:的方法
- (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);
}
}];
}
}
}
【问题讨论】:
标签: ios objective-c nsurlconnection nsurlrequest