请求代码在那里:
// 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,但这对你知道什么是一个巨大的痛苦.
如果您有任何想法,那将会有很大帮助.谢谢!
解决方法
[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