objective-c – 未调用NSURLConnection didReceiveData

前端之家收集整理的这篇文章主要介绍了objective-c – 未调用NSURLConnection didReceiveData前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经阅读了大量的消息再次说同样的事情:当你使用NSURLConnection时,不会调用委托方法.我理解Apple的文档是不完整的并且引用了弃用的方法,这是一种耻辱,但我似乎无法找到解决方案.

请求代码在那里:

// Create request
NSURL *urlObj = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlObj cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];

if (![NSURLConnection canHandleRequest:request]) {
    NSLog(@"Can't handle request...");
    return;
}

// Start connection
dispatch_async(dispatch_get_main_queue(),^{
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; // Edited
});

…代理方法代码在这里:

- (void) connection:(NSURLConnection *)_connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"Receiving response: %@,status %d",[(NSHTTPURLResponse*)response allHeaderFields],[(NSHTTPURLResponse*) response statusCode]);
    self.data = [NSMutableData data];
}

- (void) connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error {
    NSLog(@"Connection Failed: %@",error);
    [self _finish];
}

- (void) connection:(NSURLConnection *)_connection didReceiveData:(NSData *)_data {
    [data appendData:_data];
}

- (void)connectionDidFinishDownloading:(NSURLConnection *)_connection destinationURL:(NSURL *) destinationURL {
    NSLog(@"Connection done!");
    [self _finish];
}

这里没有很多错误检查,但我确定了一些事情:

>无论发生什么,都不会调用didReceiveData,所以我没有得到任何数据
> …但数据已转移(我使用tcpdump检查)
> …并成功调用其他方法.
>如果我使用NSURLConnectionDownloadDelegate而不是NSURLConnectionDataDelegate,一切正常但我无法保留下载的文件(这是一个已知的bug)
>在内存管理不良之前,请求不会被释放
>如果我在互联网上的某个地方使用标准HTML页面作为我的URL,则没有任何变化
>请求从主队列中启动

我不想使用第三方库,因为最终,这些请求将被包含在我自己的库中,并且我想最小化依赖性.如果必须的话,我会直接使用CFNetwork,但这对你知道什么是一个巨大的痛苦.

如果您有任何想法,那将会有很大帮助.谢谢!

解决方法

我喜欢使用sendAsynchronousRequest方法..在连接过程中信息较少,但代码更清晰.
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
        if (data){
            //do something with data
        }
        else if (error)
            NSLog(@"%@",error);
    }];

来自Apple:

By default,a connection is scheduled on the current thread in the
default mode when it is created. If you create a connection with the
initWithRequest:delegate:startImmediately: method and provide NO for
the startImmediately parameter,you can schedule the connection on a
different run loop or mode before starting it with the start method.
You can schedule a connection on multiple run loops and modes,or on
the same run loop in multiple modes.

除非有理由在[NSRunLoop currentRunLoop]中明确运行它,
你可以删除这两行:

[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];

或将模式更改为NSDefaultRunLoopMode

原文链接:https://www.f2er.com/c/116514.html

猜你在找的C&C++相关文章