NSURLConnection sendAsynchronousRequest没有得到响应

时间:2014-01-28 22:30:26

标签: ios objective-c nsurlconnection nsurlrequest

我有一个创建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);
                                       }
                                   }];
        }
    }
}

1 个答案:

答案 0 :(得分:2)

一般注意事项: 您的网络请求的完成块正在捕获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) {...}];