NSUrlConnection不起作用。我没有得到任何回应

问题描述:

在我的课堂我创建了一个CBUrlConnection:NSUrlConnection不起作用。我没有得到任何回应

urlConnection = [NSURLConnection connectionWithRequest:request delegate:self]; 
[urlConnection start]; 

,但我没有得到任何回应,这些委托方法是永远不会调用:

- (void)connection:(NSURLConnection *)connection didFinishLoadingData:(NSData *)data error:(NSError *)error 
- (void)connection:(NSURLConnection *)connection didUpdateProgress:(CGFloat)percent 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 

请求似乎是正确的,服务器的URL肯定是正确的,并且服务器工作正常。什么可能是错的?

+0

你加'NSURLConnectionDelegate'到类采用协议列表中? – Alexander

+0

你想尝试使用NSOperation子类中的连接吗? – Karl

我刚刚修复了它......这是因为代码没有在主线程上运行。

对于谁可能会感兴趣我和解决:

dispatch_sync(dispatch_get_main_queue(), ^{ 

}); 

可以完全从NSOperation内运行NSURLConnection。 实际技巧是NSURLConnection需要一个运行循环。见http://www.cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/https://*.com/a/6238764/171933

  • 约翰内斯