【问题标题】:NSURLConnection & UIProgressViewNSURLConnection & UIProgressView
【发布时间】:2011-12-20 02:53:47
【问题描述】:

在我的“didFinishLaunchingWithOptions”方法中,我在我的 GUI 中创建了一个 UIProgressView,然后我调用了一个方法来调用一个带有 NSURLConnection 的 WebService 来获取带有 SOAP 消息的 XML。

在委托方法“connectionDidFinishLoading”中,我在另一个类中使用 NSXMLParser 解析 XML。

问题是我想在解析 XML 时更新我的​​ UIProgressView,但是在解析整个 XML 之后它会更新。我听说这是因为 NSURLconnection 在主线程上运行并阻塞了 UI。

如何同时解析和更新进度条?

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSString * theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

NSLog( @"The XML : %@", theXML );

[theXML release];

theXmlParser = [[NSXMLParser alloc] initWithData:webData];

XMLParser * theParseur = [[XMLParser alloc] initXMLParser];

[theXmlParser setDelegate:theParseur];

[theXmlParser setShouldProcessNamespaces:NO];
[theXmlParser setShouldReportNamespacePrefixes:NO];
[theXmlParser setShouldResolveExternalEntities:NO];

NSLog(@"Begin parsing...");

BOOL success = [theXmlParser parse];

if( success ) {

    // my code...

} else {

    NSLog(@"XML partner : End Parsing > ERROR : %@", [[theXmlParser  parserError] localizedDescription] );

    [theXmlParser release];
}

[connection release];
[webData release];
}

【问题讨论】:

    标签: objective-c nsurlconnection uiprogressview


    【解决方案1】:

    NSURLConnection 在加载数据时不会阻塞主线程,但你在connectionDidFinishLoading: 中所做的所有事情都会阻塞。如果您知道文档中可能有多少元素,您可以使用NSXMLParserDelegate 回调:- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict 来保持看到元素的运行总数,“完成百分比”将是该数字除以元素总数.然后,您可以在该回调中更新进度条。

    如果不知道文档的先验长度,就很难估计文档的处理进度,除非您保留已处理的总字节数。

    【讨论】:

      【解决方案2】:

      您好,您可以在
      -(void)connection:(NSURLConnection *)connection didReceiveData: (NSData *)data { //update progress bar here
      }

      中更新进度条

      【讨论】:

      • 感谢您的回复!但我不想在接收 XML 但在“connectionDidFinishLoading”中解析它时更新进度条。你明白吗?
      • ok..parsing....为此,您必须在各个点更新进度条...分享您收到响应的代码...。
      • - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [webData setLength:0]; (对不起,我不知道如何包装我的代码以便更好地阅读......)
      • sorry sorry...我的意思是 connectionDidFinishLoading 方法..对于可读代码,请编辑您的问题并添加代码
      • 在我的 XMLParser 类的“didEndElement”委托方法中。每次遇到特殊标签时,我都会这样做:“pgrView.progress = /*my updated float*/”
      猜你喜欢
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多