【问题标题】:IOS: how can i refresh UI with async TBXML-callIOS:如何使用异步 TBXML 调用刷新 UI
【发布时间】:2012-09-11 14:10:22
【问题描述】:

我正在使用 TBXML 解析 http-XML 文件并在 UILabel 和 UIImageView 中显示内容。 对 XML 的调用是通过异步请求完成的。

当我查看日志时,succesblock 中的最后一个日志元素会立即打印出来。 UILabel 和 UIImageview 中的更改仅在几秒钟后可见。

如何让IOS在处理完XML后直接刷新UI?

// Create a success block to be called when the async request completes
TBXMLSuccessBlock successBlock = ^(TBXML *tbxmlDocument) {
    // If TBXML found a root node, process element and iterate all children
    NSLog(@"PROCESSING ASYNC CALLBACK");
    if (tbxmlDocument.rootXMLElement)
        [self traverseElement:tbxmlDocument.rootXMLElement];

    myArticle.Body = [[StringCleaner sharedInstance] cleanedString:myArticle.Body];
   // myArticle.Body = [myArticle.Body stringByConvertingHTMLToPlainText];
    self.articleBody.text = myArticle.Body;
    self.articleBody.numberOfLines= 0;
    self.articleBody.lineBreakMode = UILineBreakModeWordWrap;
    [self.articleBody sizeToFit];

    // set scroll view size
    self.articleBodyScrollView.contentSize = CGSizeMake(self.articleBodyScrollView.contentSize.width, self.articleBody.frame.size.height);

    NSURL *url = [NSURL URLWithString:myArticle.Photo];
    NSData *data = [NSData dataWithContentsOfURL:url];
    if (data != NULL)
    {
        UIImage *image = [UIImage imageWithData:data];
        // articlePhoto = [[UIImageView alloc] initWithImage:image];
        [self.articlePhoto setImage:image];
    }else {
        NSLog(@"no data");
    }

    NSLog(@"FINISHED PROCESSING ASYNC");


    // [self printArticles];
};

// Create a failure block that gets called if something goes wrong
TBXMLFailureBlock failureBlock = ^(TBXML *tbxmlDocument, NSError * error) {
    NSLog(@"Error! %@ %@", [error localizedDescription], [error userInfo]);
};

// tbxml = [[TBXML alloc] initWithURL:[NSURL URLWithString:someXML]];
tbxml = [[TBXML alloc] initWithURL:[NSURL URLWithString:records] 
                           success:successBlock 
                           failure:failureBlock];

【问题讨论】:

    标签: objective-c ios tbxml


    【解决方案1】:

    听起来您尝试更新 UI,但不是在 UI 线程上。将您的 UILabel 和 UIImageView 更新包装到主线程上的 dispatch_async 中,例如:

    dispatch_async(dispatch_get_main_queue(), ^
    {
     [self.articlePhoto setImage:image];
    });
    

    【讨论】:

    • 你能再解释一下吗?我在哪里添加 dispatch_async 代码?在 TBXML 的 succesblock 中?
    猜你喜欢
    • 2010-09-20
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多