2012-10-15 34 views
0

我正在使用NSURLConnection异步调用来从服务器加载数据。在调用服务方法与performSelectorInBackground,该方法被调用,但NSURLConnection不提供任何response.I使用异步调用,因为我必须首先验证身份验证。每当我在主线程上尝试服务调用时,都会给我正确的数据,但UI会冻结。 1)如何使用performSelectorInBackground进行异步调用 通过异步加载数据,我在做什么错误。如何使用NSOperationQueue或performSelectorInBackground运行异步服务调用

任何帮助将不胜感激

回答

0

这是一个可行的办法,虽然不是通过NSURLConnection的,但它不会阻止:

NSURL *xmlURL = [NSURL URLWithString:URL]; 

if (self.xmlParser != nil) 
{ 
    [self.xmlParser abortParsing]; 
    self.xmlParser = nil; 
} 

dispatch_queue_t loadQueue1 = dispatch_queue_create("loadQueue1", NULL); 

// Use another thread to avoid blocking main thread 

dispatch_async(loadQueue1,^{ 

self.xmlParser = [[[NSXMLParser alloc] initWithContentsOfURL:xmlURL] autorelease]; 

// ------------------------------------------------------------------- 
[self.xmlParser setDelegate:self]; 


dispatch_async(dispatch_get_main_queue(),^{ 
if (self.xmlParser != nil) 
{ 
    [self.xmlParser parse]; 
} 

    }); 


}); 

dispatch_release(loadQueue1); 
+0

谢谢凯西,但这种方式,我想我无法验证证书认证。我想要异步调用但不冻结UI。 –

0

好,调试我得到了代码error.It是后不是异步调用,但接收到巨大响应后的更新方法会冻结我的UI。另外,我用来打印数据的NSLog导致此问题。

0

如果您将异步API用于NSURLConnection,则不需要使用performSelectorInBackground。您可以从主线程调用它,然后设置委托,在数据即将到来或发生其他事件时调用委托,而不会阻塞主线程。