我有一个创建一个的方法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);
}
}];
}
}
}
一般注意事项:您的网络请求完成块正在捕获self
。这将导致保留周期。
^(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);
}
}
要修复它,您应该__weak MyClass *weakSelf = self;
在块之前声明一个变量,并且只能在块内使用它。
您的特定问题可能与所调用的文档类型无关,而与所调用的线程有关。您正在上执行网络操作[NSOperationQueue currentQueue]
。如果这是系统队列,则可能在请求完成之前将其释放。您应该声明一个属性,NSOperationQueue
并对其执行所有网络请求。
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {...}];
应更改为:
[NSURLConnection sendAsynchronousRequest:request
queue:self.networkOpQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {...}];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句