ios - 在iOS中通过同步下载更新进度指示器,无法在主线程上更新UI?

标签 ios objective-c nsdata

我在执行同步下载时无法更新UI时遇到问题。我希望使用同步API可以确保代码按顺序执行(这似乎没有执行),这确实让我感到困惑。

以下代码位于UICollectionView的didSelectItemAtIndexPath中,并且没有包装在任何异步块中。

关于执行这些任务时如何更新UI(最重要的是进度指示器),我有什么想法?我认为当前布局的方式应该可以,但是由于某种原因,直到代码全部“执行”后,它才能更新。

if ([internetReachable isReachable]) {
    //does not become visible until after
    self.circleProgress.alpha = 1.0;

    //lots of downloading and saving with NSData dataWithContentsOfURL followed by this: 

    for (int i = 1; i < pages.count; i++) {
        NSString *number;
        if (i < 10) {
            number = [NSString stringWithFormat:@"00%d", i];
        }
        else if (i < 100) {
            number = [NSString stringWithFormat:@"0%d", i];
        }
        else {
            number = [NSString stringWithFormat:@"%d", i];
        }
        NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://books.hardbound.co/%@/%@-%@.png", slug, slug, number]];
        NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

        [df setObject:imageData forKey:[NSString stringWithFormat:@"%@-%@", slug, number]];

        CGFloat progress = ((CGFloat)i / pages.count);
//only runs for the last iteration, rather than calling the method to update the progress indicator each iteration and allowing it to update before going back to the next iteration as I would expect
        [self updateProgressBarWithAmount:[NSNumber numberWithFloat:progress]];

        NSLog(@"progress after: %f", self.circleProgress.progress);
    }   
}

最佳答案

UI只能在主线程上执行。由于主线程正忙于进行下载,因此无法更新UI。在主线程上执行任何长时间运行的操作几乎从来不是一个好主意。您应该使下载异步,并在主线程上更新UI。

您发布的代码中的循环将仅在执行lots of downloading and saving with NSData dataWithContentsOfURL之后执行,同时应用程序将一直无响应,这是非常糟糕的UX。查看this question,以更好地实现进度条。

关于ios - 在iOS中通过同步下载更新进度指示器,无法在主线程上更新UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869084/

相关文章:

ios - Swift - 通过定义的点/区域检测用户绘图。

iphone - ios中的webservice中的多个参数

ios - 错误为 "The operation couldn’ 的 NSData 无法完成。 ( cocoa 错误 256。)”

swift - 将对象作为类存储到文件中

ios - Xcode4:构建 IPA 的替代方法

ios - MKMapView - 有没有办法将 MKUserTrackingModeFollow 与修改的中心/焦点一起使用?

ios - 使用 parse.com 在应用程序中处理推送通知

ios - UIImagePickerController 正确地在其上叠加图像

ios - 为什么我的 Tweak 不能正常工作?

objective-c - 如何串联多个NSData?