gpt4 book ai didi

objective-c - NSURLConnection didReceiveData 未调用

转载 作者:可可西里 更新时间:2023-11-01 03:37:36 25 4
gpt4 key购买 nike

我通读了大量的消息,一遍又一遍地说同样的话:当你使用 NSURLConnection 时,委托(delegate)方法不会被调用。我知道 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
});

...委托(delegate)方法的代码在这里:

- (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,一切正常,但我无法保留下载的文件(这是一个已知错误)
  • 由于错误的内存管理,请求在完成之前未被释放
  • 如果我使用互联网上某处的标准 HTML 页面作为我的 URL,则没有任何变化
  • 请求从主队列中启动

我不想使用第三方库,因为最终这些请求将包含在我自己的库中,我想尽量减少依赖性。如果必须的话,我会直接使用 CFNetwork,但这将是您所知道的巨大痛苦。

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

最佳答案

我遇到了同样的问题。很烦人,但似乎如果你实现这个方法:

- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL

那么 connection:didReceiveData: 永远不会被调用。您必须使用 connectionDidFinishLoading: 代替...是的,文档说它已被弃用,但我认为那只是因为此方法从 NSURLConnectionDelegate 移动到 NSURLConnectionDataDelegate.

关于objective-c - NSURLConnection didReceiveData 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11420469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com